【问题标题】:Overriden method still gets called被覆盖的方法仍然被调用
【发布时间】:2013-09-08 10:04:05
【问题描述】:

我正在使用一个库,该库在数据库中的两个条目之间实现belongs_to 关联。由于这不是我需要的行为,我想通过prepend 覆盖此方法。但是 pry 告诉我原来的方法仍然被调用。我仔细检查了一下,我使用的是 ruby​​ 2.0。

前面的代码:

module Associations
  module ClassMethods

    [...]
    #Add the attributeName to the belongsToAttributes
    #and add a field in the list for the IDs
    def belongs_to(attr_name)
      @belongsToAttributes ||= []
      @belongstoAttributes << attr_name

      create_attr attr_name.to_s
      attribute belongs_to_string.concat(attr_name.to_s).to_sym
    end

    def belongsToAttributes
      @belongsToAttributes
    end    
  end

  def self.included(base)
    base.extend(ClassMethods)
  end
end

# prepend the extension 
Couchbase::Model.send(:prepend, Associations)

我在这个课程中使用这个:

注意:我也试过直接覆盖这个类中的方法,但是还是没有发生

require 'couchbase/model'

class AdServeModel < Couchbase::Model

[...]
  #I tried to add the belongs_to method like this
  #def belongs_to(attr_name)
  #   @belongsToAttributes ||= []
  #   @belongstoAttributes << attr_name

  #   create_attr attr_name.to_s
  #    attribute belongs_to_string.concat(attr_name.to_s).to_sym
  #  end

  #  def belongsToAttributes
  #    @belongsToAttributes
  #  end
end

当我使用 pry 检查时,它显示我最终进入了 this 方法调用:

def self.belongs_to(name, options = {})
  ref = "#{name}_id"
  attribute(ref)
  assoc = name.to_s.camelize.constantize
  define_method(name) do
    assoc.find(self.send(ref))
  end
end

任何指向我做错了什么的指针都将不胜感激。

编辑: 好的,我解决了这样的问题:

 self.prepended(base)
    class << base
      prepend ClassMethods
    end
  end

end
# prepend the extension 
Couchbase::Model.send(:prepend, Associations)

由于 Arie Shaw 的帖子包含解决此问题的重要指示,我将接受他的回答。尽管他错过了关于扩展和预先设置我要调用的方法的要点。有关我在添加方法时遇到的麻烦的更详细讨论,请参阅this 问题。

【问题讨论】:

    标签: ruby-on-rails ruby couchbase ruby-2.0


    【解决方案1】:

    根据您发布的 pry trace,您要猴子补丁的方法是 AdServeModel 的类方法,而不是实例方法。

    • 你的 Associations 模块方法的问题是,你正在调用 Module#prepend 到 prepend 模块到现有的类,但是,你写了一个 self.included 钩子方法,只有在该模块被包括在内(不是前置)。你应该改写Module#prepended hook。

    • 直接覆盖方法的问题是,您实际上是在覆盖实例方法,而不是类方法。应该是这样的:

    require 'couchbase/model'
    
    class AdServeModel < Couchbase::Model
      class << self
        # save the original method for future use, if necessary
        alias_method :orig_belongs_to, :belongs_to
    
        def belongs_to(attr_name)
          @belongsToAttributes ||= []
          @belongstoAttributes << attr_name
    
          create_attr attr_name.to_s
          attribute belongs_to_string.concat(attr_name.to_s).to_sym
        end
    
        def belongsToAttributes
          @belongsToAttributes
        end
      end
    end
    

    【讨论】:

    • 哦,是的,我知道了,我想它叫alias_method_chaining?我实际上试图避免这种情况。我已经将钩子更改为 Module#prepend 但无济于事。请参考stackoverflow.com/questions/18683750/…问题,我试图在其中找到更基本问题的答案。
    猜你喜欢
    • 2011-12-13
    • 1970-01-01
    • 2014-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-29
    • 2013-06-02
    • 2011-11-10
    相关资源
    最近更新 更多