DEV Community

n350071🇯🇵
n350071🇯🇵

Posted on

define_method (write once, run everywhere!)

Basic

# The |obj| is argument, for in this example, it will represents after_save(obj).
[:after_save].each do |method|
  define_method method do |obj|
    @title, @body = obj.title, obj.body
    mail(to: @user.email, subject: 'Hello')
  end
end
Enter fullscreen mode Exit fullscreen mode

Variation

1. Status Encapsulation

# also, you can do this.
class Mode
  [:low, :middle, :high].each do |level|
    define_method(level) do
      @state = level
    end
  attr_reader :state
  end
end

log = Mode.new
log.low
log.state    #=>low
log.middle
log.state    #=>middle
log.high
log.state    #=>high
Enter fullscreen mode Exit fullscreen mode

2. only the name is different


🔗 Parent Note

Top comments (0)