ruby​​/datamapper:重构类方法到模块

问题描述:

我已经下面的代码,并尝试了整整一天的重构类方法到一个sperate模块与我的所有模型类共享功能。ruby​​/datamapper:重构类方法到模块

码(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) 

但不幸的是,我的红宝石技能是不好的。我读了很多东西(例如here),现在我更加困惑。我绊了以下两点:

  1. alias_method会失败,因为它会在DataMapper::Resource模块中动态定义。
  2. 如何获得包含模块的类方法allowed_properties

什么是红宝石的方式去?

非常感谢提前。

Here是关于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 

因为它使用继承的形式可以采取的,而不是使用alias_method,其中许多人发现更直截了当的super优势。

使用ModuleName::ClassMethods是您在Rails代码库中看到的很多东西,并且使其更容易使用super