ruby-on-railsalias-method-chain

Rails - alias_method_chain with a 'attribute=' method


I'd like to 'add on' some code on a model's method via a module, when it is included. I think I should use alias_method_chain, but I don't know how to use it, since my 'aliased method' is one of those methods ending on the '=' sign:

class MyModel < ActiveRecord::Base

  def foo=(value)
    ... do stuff with value
  end

end

So this is what my module looks right now:

module MyModule
  def self.included(base)
    base.send(:include, InstanceMethods)
    base.class_eval do

      alias_method_chain 'foo=', :bar

    end
  end

  module InstanceMethods
    def foo=_with_bar(value) # ERROR HERE
      ... do more stuff with value
    end
  end
end

I get an error on the function definition. How do get around this?


Solution

  • alias_method_chain is a simple, two-line method:

    def alias_method_chain( target, feature )
      alias_method "#{target}_without_#{feature}", target
      alias_method target, "#{target}_with_#{feature}"
    end
    

    I think the answer you want is to simply make the two alias_method calls yourself in this case:

    alias_method :foo_without_bar=, :foo=
    alias_method :foo=, :foo_with_bar=
    

    And you would define your method like so:

    def foo_with_bar=(value)
      ...
    end
    

    Ruby symbols process the trailing = and ? of method names without a problem.