Class: PapersPlease::Role

Inherits:
Object
  • Object
show all
Defined in:
lib/papers_please/role.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, predicate: nil) ⇒ Role

Returns a new instance of Role.



5
6
7
8
9
# File 'lib/papers_please/role.rb', line 5

def initialize(name, predicate: nil)
  @name = name
  @predicate = predicate
  @permissions = []
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



3
4
5
# File 'lib/papers_please/role.rb', line 3

def name
  @name
end

#permissionsObject (readonly)

Returns the value of attribute permissions.



3
4
5
# File 'lib/papers_please/role.rb', line 3

def permissions
  @permissions
end

#predicateObject (readonly)

Returns the value of attribute predicate.



3
4
5
# File 'lib/papers_please/role.rb', line 3

def predicate
  @predicate
end

Instance Method Details

#add_permission(actions, klass, query: nil, predicate: nil, granted_by: nil) ⇒ Object Also known as: grant



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/papers_please/role.rb', line 17

def add_permission(actions, klass, query: nil, predicate: nil, granted_by: nil)
  prepare_actions(actions).each do |action|
    raise DuplicatePermission if permission_exists?(action, klass)

    if !granted_by.nil? && !valid_grant?(granted_by)
      raise InvalidGrant,
            'granted_by must be an array of [Class, Proc]'
    end

    permissions << make_permission(
      action,
      actions,
      klass,
      query: query,
      predicate: predicate,
      granted_by: granted_by
    )
  end
end

#applies_to?(user) ⇒ Boolean

Returns:

  • (Boolean)


11
12
13
14
15
# File 'lib/papers_please/role.rb', line 11

def applies_to?(user)
  return @predicate.call(user) if @predicate.is_a? Proc

  true
end

#find_permission(action, subject) ⇒ Object



38
39
40
41
42
# File 'lib/papers_please/role.rb', line 38

def find_permission(action, subject)
  permissions.detect do |permission|
    permission.matches? action, subject
  end
end

#permission_exists?(action, subject) ⇒ Boolean

Returns:

  • (Boolean)


44
45
46
# File 'lib/papers_please/role.rb', line 44

def permission_exists?(action, subject)
  !find_permission(action, subject).nil?
end