Module: Aegis::HasRole

Defined in:
lib/aegis/has_role.rb

Instance Method Summary collapse

Instance Method Details

#has_role(options = {}) ⇒ Object



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
# File 'lib/aegis/has_role.rb', line 14

def has_role(options = {})

  if options[:name_accessor]
    options[:name_reader] = "#{options[:name_accessor]}"
    options[:name_writer] = "#{options[:name_accessor]}="
    options.delete(:name_accessor)
  end

  self.class_eval do

    class_inheritable_accessor :aegis_role_name_reader, :aegis_role_name_writer

    self.aegis_role_name_reader = (options[:name_reader] || "role_name").to_sym
    self.aegis_role_name_writer = (options[:name_writer] || "role_name=").to_sym

    def aegis_role_name_reader
      self.class.class_eval{ aegis_role_name_reader }
    end

    def aegis_role_name_writer
      self.class.class_eval{ aegis_role_name_writer }
    end

    def aegis_role_name
      send(aegis_role_name_reader)
    end

    def aegis_role_name=(value)
      send(aegis_role_name_writer, value)
    end

    def role
      ::Permissions.find_role_by_name!(aegis_role_name)
    end

    def role=(role_or_name)
      self.aegis_role_name = if role_or_name.is_a?(Aegis::Role)
        role_or_name.name
      else
        role_or_name.to_s
      end
    end

    private

    # Delegate may_...? and may_...! methods to the user's role.
    def method_missing_with_aegis_permissions(symb, *args)
      method_name = symb.to_s
      if method_name =~ /^may_(.+?)[\!\?]$/
        role.send(symb, self, *args)
      elsif method_name =~ /^(.*?)\?$/ && queried_role = ::Permissions.find_role_by_name($1)
        role == queried_role
      else
        method_missing_without_aegis_permissions(symb, *args)
      end
    end

    alias_method_chain :method_missing, :aegis_permissions

    def respond_to_with_aegis_permissions?(symb, include_private = false)
      if symb.to_s =~ /^may_(.+?)[\!\?]$/
        true
      else
        respond_to_without_aegis_permissions?(symb, include_private)
      end
    end

    alias_method_chain :respond_to?, :aegis_permissions

    def set_default_aegis_role_name
      if new_record?
        self.aegis_role_name ||= self.class.aegis_default_role_name
      end
    end

  end

end

#validates_role_name(options = {}) ⇒ Object Also known as: validates_role



4
5
6
7
8
9
10
# File 'lib/aegis/has_role.rb', line 4

def validates_role_name(options = {})
  validates_each :role_name do |record, attr, value|
    options[:message] ||= ActiveRecord::Errors.default_error_messages[:inclusion]
    role = ::Permissions.find_role_by_name(value)
    record.errors.add attr, options[:message] if role.nil?
  end
end