2010-05-24 74 views
1

我已經下面的代碼,並嘗試了整整一天的重構類方法到一個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

什麼是紅寶石的方式去?

非常感謝提前。

回答

0

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