Use def_method inside ActiveRecord model

2019-08-31 05:52发布

问题:

So I have AR model like the following, and I want to dynamically generate a few instance methods like #fallbackable_header_script, #fallbackable_header_content... etc, just like the #fallbackable_background I've already written. What's the best way to do this?

class Course < ActiveRecord::Base
  FALLBACKABLE_ATTRIBUTES = :header_script, :header_content, :footer_content
  OTHER_FALLBACKABLE_ATTRIBUTES = :css_config

  def fallbackable_background
    read_attribute(:background) ? background : self.user.background
  end

end

I tried def_method, but the following doesn't work...

  [:foo, :bar].each do |meth|
    fallbackable_meth = "fallbackable_#{meth}".to_sym
    def_method(fallbackable_meth) { read_attribute(meth) ? read_attribute(meth) : self.user.send(meth) }
  end
  #=>NoMethodError: undefined method `def_method' for #<Class:0x007fe4e709a208>

回答1:

I think its define_method and not def_method

[:foo, :bar].each do |meth|
    fallbackable_meth = "fallbackable_#{meth}".to_sym
    define_method(fallbackable_meth) { read_attribute(meth) ? read_attribute(meth) : self.user.send(meth) }
  end

You can also use def_each to define similar methods

def_each :fallbackable_foo, :fallbackable_bar do |method_name|
 read_attribute(method_name) ? read_attribute(method_name) : self.user.send(method_name)
end