简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM