Module: Royce::ClassMethods

Defined in:
lib/royce/class_methods.rb

Class Method Summary collapse

Class Method Details

.included(includer) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/royce/class_methods.rb', line 3

def self.included includer
  includer.class_eval do

    # Add relations to including class
    has_many :role_connectors, as: :roleable, class_name: 'Royce::Connector'
    has_many :roles, through: :role_connectors, class_name: 'Royce::Role'

    # Add class method to return all possible roles
    def self.available_roles
      self.available_role_names.map{ |name| Role.find_or_create_by(name: name) }
    end

    # Add scopes to including class
    # User.admins
    # User.editors
    available_role_names.each do |role_name|
      includer_class_name = includer.model_name.to_s.underscore.pluralize
      scope role_name.pluralize, -> { Role.find_by(name: role_name).send includer_class_name.to_sym }
    end

  end

  # Be able to search some_role.users and get back instnaces of User
  # Royce::Role.find_by(name, 'admin').users
  Royce::Role.class_eval do
    has_many includer.model_name.to_s.underscore.pluralize.to_sym, through: :connectors, source: :roleable, source_type: includer.model_name.to_s
  end

end