2011-06-02 54 views
0

問題下面是我遇到的問題: https://gist.github.com/1003813Rails的:我在與遺傳協會

假設你有一個派生類:

class User < ActiveRecord::Base 
include ThisThing 
include ThatThing 

[...] 

end 

class OurUser < User 
set_table_name 'users' 

[...] 

end 

我需要一些協會,例如:

belongs_to :friend, 
     :class_name => 'User', 
     :foreign_key => :friend_of 

問題我如果這是在User類中聲明的,OurUser的朋友將是一個User,並且不會在OurUser中包含任何額外的方法。當然,在編寫User類時,您不知道正確的類名。

我需要我怎樣才能讓它在一些suggestons所以OurUser將有正確的類

回答

0

的.friend與所有的共享行爲創建一個模塊,並使用模塊#包括鉤來動態定義的相關項目在包括。即:

module SharedBehaviour 
    def self.included(base) 
    base.class_eval do 
     set_table_name 'users'   

     belongs_to :friend, :class_name => base.name, :foreign_key => :friend_of 

     include ThisThing 
     include ThatThing 

     # other class method calls go here (validations, etc) 
    end 
    end 

    module ClassMethods 
    # shared class methods go here 
    end 

    # shared instance methods go here 
end 

class User < ActiveRecord::Base 
    inclde SharedBehaviour 
end 

class OtherUser < ActiveRecord::Base 
    include SharedBehaviour 
end