2010-05-24 1 views
1

다음 코드를 사용하여 모든 모델 클래스와 기능을 공유하기 위해 클래스 메소드를 리펙토링하기 위해 하루 종일 노력했습니다.ruby ​​/ datamapper : 모듈에 클래스 메소드 리팩터링

코드 (http://pastie.org/974847는) :

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) 

그러나 불행하게도, 내 루비 기술 나쁜에 있습니다

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  

내가 좋아하는 뭔가를 보관하고 싶습니다. 많은 물건 (예 : here)을 읽었으며 이제는 더 혼란 스럽습니다. 나는 다음과 같은 두 지점을 통해 발견 :

  1. alias_method이 실패합니다, 그것은 동적으로 DataMapper::Resource 모듈에 정의 된 때문입니다.
  2. 모듈을 포함하여 allowed_properties 클래스 메서드를 얻는 방법?

루비 방법은 무엇입니까?

미리 감사드립니다.

답변

0

Here은 루비 클래스 메서드 모듈 상속에 대한 훌륭한 토론입니다. 이 같은 뭔가 일할 수 :

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을 사용하면 레일스 코드베이스에서 많이 볼 수 있으며 super을 더 쉽게 사용할 수 있습니다.