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 )

但不幸的是,我的红宝石技能太差了。我读了很多东西(例如这里),现在我更加困惑了。我偶然发现了以下两点:

  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而不是 using alias_method,许多人发现这更直接。

UsingModuleName::ClassMethods是你在 Rails 代码库中经常看到的东西,它使它更易于使用super

于 2010-05-24T20:50:30.320 回答