【发布时间】:2013-07-10 21:18:43
【问题描述】:
所以我有如下的 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>
【问题讨论】:
标签: ruby-on-rails ruby metaprogramming