Module: EasyRoles::ClassMethods

Defined in:
lib/easy_roles.rb

Instance Method Summary collapse

Instance Method Details

#easy_roles(name, options = {}) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/easy_roles.rb', line 9

def easy_roles(name, options = {})
  
  options[:method] ||= :serialize
  
  if options[:method] == :serialize
    serialize name.to_sym, Array
    
    ActiveSupport::Deprecation.silence do
      respond_to?(:before_validation_on_create) ? before_validation_on_create(:make_default_roles) : before_validation(:make_default_roles, :on => :create)
    end
    
    class_eval <<-EOC
      def has_role?(role)
        #{name}.include?(role)
      end

      def add_role(role)
        clear_roles if self.#{name}.nil?
        has_role?(role) ? false : self.#{name} << role
      end
    
      def add_role!(role)
        add_role(role)
        self.save!
      end

      def remove_role(role)
        self.#{name}.delete(role)
      end
    
      def remove_role!(role)
        remove_role(role)
        self.save!
      end
    
      def clear_roles
        self.#{name} = []
      end
    
      def make_default_roles
        clear_roles if #{name}.nil?
      end
    
      private :make_default_roles
    EOC
  elsif options[:method] == :bitmask
    
    def_name = (name == :roles) ? :easy_roles : :roles
    
    class_eval <<-EOC
      def self.list_roles
        #{name.to_s.upcase}
      end
    
      def #{def_name}=(roles)
        self.#{name} = (roles & #{name.to_s.upcase}).map { |r| 2**#{name.to_s.upcase}.index(r) }.sum
      end

      def #{def_name}
        #{name.to_s.upcase}.reject { |r| ((#{name} || 0) & 2**#{name.to_s.upcase}.index(r)).zero? }
      end
      
      def has_role?(role)
        #{def_name}.include?(role)
      end
      
      def add_role(role)
        new_roles = #{def_name}.push(role).uniq
        self.#{def_name} = new_roles
      end
      
      def add_role!(role)
        add_role(role)
        self.save!
      end
      
      def remove_role(role)
        new_roles = #{def_name}
        new_roles.delete(role)
        self.#{def_name} = new_roles
      end
      
      def remove_role!(role)
        remove_role(role)
        self.save!
      end
      
      def clear_roles
        self.#{name} = 0
      end
      
      def clear_roles!
        self.#{name} = 0
        self.save!
      end
    EOC
  end
end