【问题标题】:Rails - alias_method_chain with a 'attribute=' methodRails - alias_method_chain 带有 'attribute=' 方法
【发布时间】:2023-03-16 16:51:01
【问题描述】:

我想通过模块在模型的方法上“添加”一些代码,当它被包含时。我想我应该使用 alias_method_chain,但我不知道如何使用它,因为我的“别名方法”是以“=”符号结尾的方法之一:

class MyModel < ActiveRecord::Base

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

end

这就是我的模块现在的样子:

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

函数定义出错。如何解决这个问题?

【问题讨论】:

    标签: ruby-on-rails alias-method-chain


    【解决方案1】:

    alias_method_chain 是一个简单的两行方法:

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

    我认为你想要的答案是在这种情况下简单地让两个alias_method 调用你自己:

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

    你会像这样定义你的方法:

    def foo_with_bar=(value)
      ...
    end
    

    Ruby 符号可以毫无问题地处理方法名称的结尾 =?

    【讨论】:

    • 谢谢杰米!这正是我想要的。
    • alias_method_chain 不是简单的两行方法(还有吗?),它应该按预期处理 = 符号(即创建 foo_with_bar= 和 foo_without_bar=)
    猜你喜欢
    • 1970-01-01
    • 2018-10-30
    • 2019-04-17
    • 2019-08-21
    • 1970-01-01
    • 1970-01-01
    • 2011-05-20
    • 2013-08-12
    • 1970-01-01
    相关资源
    最近更新 更多