我有一个包含模块的模型。我想在模块中覆盖模型的访问器方法。
例如:
class Blah < ActiveRecord::Base
include GnarlyFeatures
# database field: name
end
module GnarlyFeatures
def name=(value)
write_attribute :name, "Your New Name"
end
end
这显然是行不通的。有什么想法可以做到这一点吗?
我有一个包含模块的模型。我想在模块中覆盖模型的访问器方法。
例如:
class Blah < ActiveRecord::Base
include GnarlyFeatures
# database field: name
end
module GnarlyFeatures
def name=(value)
write_attribute :name, "Your New Name"
end
end
这显然是行不通的。有什么想法可以做到这一点吗?
您的代码看起来正确。我们使用这种精确的模式没有任何麻烦。
如果我没记错的话,Rails 使用 #method_missing 作为属性设置器,所以你的模块将优先,阻止 ActiveRecord 的设置器。
如果您使用 ActiveSupport::Concern(请参阅此博客文章,那么您的实例方法需要进入一个特殊模块:
class Blah < ActiveRecord::Base
include GnarlyFeatures
# database field: name
end
module GnarlyFeatures
extend ActiveSupport::Concern
included do
def name=(value)
write_attribute :name, value
end
end
end