Override model's attribute accessor in a mixin/module
ruby, ruby-on-rails
Solution
Your code looks correct. We are using this exact pattern without any trouble.
If I remember right, Rails uses #method_missing for attribute setters, so your module will take precedence, blocking ActiveRecord's setter.
If you are using ActiveSupport::Concern (see this blog post, then your instance methods need to go into a special module:
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
Problem
I have a model which includes a module. I'd like to override the model's accessor methods within the module. For example: ``` class Blah < ActiveRecord::Base include GnarlyFeatures # database field: name end module GnarlyFeatures def name=(value) write_attribute :name, "Your New Name" end end ``` This obviously doesn't work. Any ideas for accomplishing this?