Module: AccessGranted::Policy

Included in:
AccessPolicy
Defined in:
lib/access-granted/policy.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#cacheObject

Returns the value of attribute cache.



3
4
5
# File 'lib/access-granted/policy.rb', line 3

def cache
  @cache
end

#rolesObject

Returns the value of attribute roles.



3
4
5
# File 'lib/access-granted/policy.rb', line 3

def roles
  @roles
end

#userObject (readonly)

Returns the value of attribute user.



4
5
6
# File 'lib/access-granted/policy.rb', line 4

def user
  @user
end

Instance Method Details

#authorize!(action, subject) ⇒ Object



48
49
50
51
52
53
# File 'lib/access-granted/policy.rb', line 48

def authorize!(action, subject)
  if cannot?(action, subject)
    raise AccessDenied
  end
  subject
end

#can?(action, subject = nil) ⇒ Boolean

Returns:

  • (Boolean)


30
31
32
33
# File 'lib/access-granted/policy.rb', line 30

def can?(action, subject = nil)
  cache[action] ||= {}
  cache[action][subject] ||= check_permission(action, subject)
end

#cannot?(*args) ⇒ Boolean

Returns:

  • (Boolean)


44
45
46
# File 'lib/access-granted/policy.rb', line 44

def cannot?(*args)
  !can?(*args)
end

#check_permission(action, subject) ⇒ Object



35
36
37
38
39
40
41
42
# File 'lib/access-granted/policy.rb', line 35

def check_permission(action, subject)
  applicable_roles.each do |role|
    permission = role.find_permission(action, subject)
    return permission.granted if permission
  end

  false
end

#configureObject



13
14
# File 'lib/access-granted/policy.rb', line 13

def configure
end

#initialize(user, cache_enabled = true) ⇒ Object



6
7
8
9
10
11
# File 'lib/access-granted/policy.rb', line 6

def initialize(user, cache_enabled = true)
  @user          = user
  @roles         = []
  @cache         = {}
  configure
end

#role(name, conditions_or_klass = nil, conditions = nil, &block) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/access-granted/policy.rb', line 16

def role(name, conditions_or_klass = nil, conditions = nil, &block)
  name = name.to_sym
  if roles.select {|r| r.name == name }.any?
    raise DuplicateRole, "Role '#{name}' already defined"
  end
  r = if conditions_or_klass.is_a?(Class) && conditions_or_klass <= AccessGranted::Role
    conditions_or_klass.new(name, conditions, user, block)
  else
    Role.new(name, conditions_or_klass, user, block)
  end
  roles << r
  r
end