3

belongs_toデータベース内の 2 つのエントリ間の関連付けを実装するライブラリを使用しています。これは私が必要とする動作ではないので、このメソッドを介してオーバーライドしたいと思います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 で確認すると、このメソッド呼び出しで終わることがわかります。

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の投稿には、この問題を解決するための重要なヒントが含まれているため、彼の回答を受け入れます。彼は、私が呼び出したいメソッドを拡張して先頭に追加することについてのポイントを逃しましたが。メソッドの先頭に追加する際の問題についての詳細な議論については、この質問を参照してください。

4

1 に答える 1