Use def_method inside ActiveRecord model

拥有回忆 提交于 2019-12-25 10:55:35

问题


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


来源:https://stackoverflow.com/questions/17581071/use-def-method-inside-activerecord-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!