开发者

Rails - alias_method_chain with a 'attribute=' method

开发者 https://www.devze.com 2022-12-16 20:38 出处:网络
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 o

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 err开发者_JAVA技巧or 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号