2013-11-01 138 views
0

在我的應用程序有兩個types用戶(運動員&用戶)。 Athlete,因爲它是使用STI設置繼承User類。還有其他類型的用戶,但這些類型的用戶是根據他們的角色設置的。Rails的:包括模塊基於角色

例子:

教練 - >Regular User with the role of 'Coach'
學校管理 - >Regular User with the role of 'School Admin'
貢獻者 - >Regular User with the role of Contributor

舊代碼中使用有Coach作爲用戶類型我的應用程序纏綿(class Coach < User; ),但是在我的應用程序中將Coach作爲單一用戶類型並沒有很大的意義。我將要採取的方法在教練模式和移動出來到一個模塊中,但很好奇,想知道有沒有辦法,包括只有當用戶有教練的角色模塊?

回答

0

是的,這是可能的。這樣做將是一個方法:

class User < ActiveRecord::Base 
    ... 
    after_initialize :extend_with_role_module 

    private 

    def extend_with_role_module 
    case role 
    when 'coach' 
     self.extend CoachModule 
    when 'school_admin' 
     self.extend SchoolAdminModule 
    when 'contributor' 
     self.extend Contributor 
    end 
    end 
    ... 
end 

但它是可怕的設計爲after_initialize塊將被要求被加載到內存中的所有User實例。該代碼可能是由於重構。

來源:Ruby 2.0.0 Docs - Object#extend