轨道:包括基于角色的模块



在我的应用程序中,有两个用户types(运动员和用户)。 Athlete继承使用 STI 设置的 User 类。还有其他类型的用户,但这些类型的用户是根据其角色设置的。

例子:

教练 --> 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 作为单个用户类型没有多大意义。我将采用 Coach 模型中的方法并将它们移到一个模块中,但我很想知道是否有办法仅在用户具有 Coach 角色时才包含模块?

是的,这是可能的。一种方法是:

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 文档 - 对象#扩展

最新更新