Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override model's attribute accessor in a mixin/module

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?

like image 315
KendallB Avatar asked May 03 '12 17:05

KendallB


1 Answers

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
like image 54
tihm Avatar answered Sep 24 '22 05:09

tihm