所以我有如下的 AR 模型,我想动态生成一些实例方法#fallbackable_header_script, #fallbackable_header_content...
,就像#fallbackable_background
我已经写的一样。最好的方法是什么?
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
我尝试了def_method,但以下不起作用......
[: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>