1

私は次のコードを作成し、クラス メソッドを個別のモジュールにリファクタリングして、すべてのモデル クラスと機能を共有するために 1 日を費やしました。

コード ( http://pastie.org/974847 ):

class Merchant
  include DataMapper::Resource

  property :id, Serial                                             
  [...]

  class << self
    @allowed_properties = [:id,:vendor_id, :identifier]

    alias_method :old_get, :get 
    def get *args
      [...]
    end         

    def first_or_create_or_update attr_hash  
      [...]
    end     
  end

end     

次のようなものをアーカイブしたいと思います:

class Merchant
  include DataMapper::Resource
  include MyClassFunctions
  [...]
end

module MyClassFunctions
  def get [...]
  def first_or_create_or_update[...]
end

=> Merchant.allowed_properties = [:id]
=> Merchant.get( :id=> 1 )

残念ながら、私の ruby​​ のスキルは低すぎます。私はたくさんのものを読みました(例:ここ)が、今はさらに混乱しています。以下の2点が気になりました。

  1. alias_methodモジュールで動的に定義されるため、失敗しDataMapper::Resourceます。
  2. allowed_propertiesモジュールを含むクラスメソッドを取得するには?

ルビーの行方は?

よろしくお願いします。

4

1 に答える 1

0

ここでは、Ruby クラス メソッド モジュールの継承に関する適切な議論を示します。このようなものはうまくいくかもしれません:

module MyFunctions
  module ClassMethods
    @allowed_properties = [:id,:vendor_id, :identifier]

    def get *args
      opts = super_cool_awesome_sauce
      super opts
    end

    def first_or_create_or_update[...]
    end
  end

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

class Merchant
  include DataMapper::Resource
  include MyFunctions
  [...]
end

継承の形式を使用しているため、多くの人がより簡単に使用できるsuperを使用する代わりに利用できます。alias_method

UsingModuleName::ClassMethodsは、Rails のコードベースでよく見られるもので、使いやすくなっていますsuper

于 2010-05-24T20:50:30.320 に答える