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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With