Module: Rolypoly::ControllerRoleDSL

Defined in:
lib/rolypoly/controller_role_dsl.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(sub) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/rolypoly/controller_role_dsl.rb', line 5

def self.included(sub)
  sub.before_filter(:rolypoly_check_role_access!) if sub.respond_to? :before_filter
  if sub.respond_to? :rescue_from
    sub.rescue_from(FailedRoleCheckError) do
      respond_to do |f|
        f.html { render text: "Not Authorized", status: 401 }
        f.json { render json: { error: "Not Authorized" }, status: 401 }
        f.xml { render xml: { error: "Not Authorized" }, status: 401 }
      end
    end
  end

  unless sub.method_defined? :current_user_roles
    define_method(:current_user_roles) { [] }
  end
  sub.send :extend, ClassMethods
  sub.class_eval do # Sometimes get Stack Too Deep errors if in ClassMethods
    define_singleton_method :inherited do |sub|
      super sub
      sub.instance_variable_set(:@rolypoly_gatekeepers, rolypoly_gatekeepers.map(&:clone))
    end
  end
end

Instance Method Details

#current_gatekeepersObject



52
53
54
55
56
# File 'lib/rolypoly/controller_role_dsl.rb', line 52

def current_gatekeepers
  rolypoly_gatekeepers.select { |gatekeeper|
    gatekeeper.action? action_name
  }
end

#current_rolesObject



37
38
39
40
41
42
43
44
45
# File 'lib/rolypoly/controller_role_dsl.rb', line 37

def current_roles
  return [] if rolypoly_gatekeepers.empty?
  current_gatekeepers.reduce([]) { |array, gatekeeper|
    if gatekeeper.role? current_user_roles
      array += Array(gatekeeper.allowed_roles(current_user_roles, action_name))
    end
    array
  }
end

#failed_role_check!Object



33
34
35
# File 'lib/rolypoly/controller_role_dsl.rb', line 33

def failed_role_check!
  raise Rolypoly::FailedRoleCheckError
end

#public?Boolean

Returns:

  • (Boolean)


47
48
49
50
# File 'lib/rolypoly/controller_role_dsl.rb', line 47

def public?
  return true if rolypoly_gatekeepers.empty?
  current_gatekeepers.any? &:public?
end

#rolypoly_check_role_access!Object



29
30
31
# File 'lib/rolypoly/controller_role_dsl.rb', line 29

def rolypoly_check_role_access!
  failed_role_check! unless rolypoly_role_access?
end