2013-11-01 64 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