Class: Scram::Policy

Inherits:
Object
  • Object
show all
Includes:
Mongoid::Document
Defined in:
lib/scram/app/models/policy.rb

Overview

Model to represent a Holder's permission policy

Instance Method Summary collapse

Instance Method Details

#can?(holder, action, obj) ⇒ Boolean

Checks if a Holder can perform some action on an object by checking targets

Parameters:

  • holder (Scram::Holder)

    The actor

  • action (String)

    What the user is trying to do to obj

  • obj (Object)

    The receiver of the action

Returns:

  • (Boolean)

    Whether or not holder can action to object


36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/scram/app/models/policy.rb', line 36

def can? holder, action, obj
  target = target.to_s if target.is_a? Symbol
  action = action.to_s if action.is_a? Symbol
  
  # The following checks prevent unnecessary iteration
  if obj.is_a? String # ex: can? :view, "peek_bar"
    return false if self.model? # policy doesn't handle strings
  else                # ex: can? :edit, @model_instance
    return false if !self.model? # policy doesn't handle models
    return false if self.collection_name != obj.class.name # policy doesn't handle these types of models
  end

  return targets.order_by([[:priority, :desc]]).any? {|target| target.can?(holder, action, obj)}
end

#collection_nameString

Returns What this Policy applies to. Usually it will be the name of a Model, but it can also be a String for a “global” policy for non model-bound permissions.

Returns:

  • (String)

    What this Policy applies to. Usually it will be the name of a Model, but it can also be a String for a “global” policy for non model-bound permissions


12
# File 'lib/scram/app/models/policy.rb', line 12

field :collection_name, type: String

#modelObject?

Attempts to constantize and get a model

Returns:

  • (Object, nil)

    An object, likely a Mongoid::Document, that this policy is bound to. nil if there is none.


23
24
25
26
27
28
29
# File 'lib/scram/app/models/policy.rb', line 23

def model
  begin
    return Module.const_get(collection_name)
  rescue NameError
    return nil
  end
end

#model?Boolean

Note:

Unnecessary since we can just call model.nil?, but it is helpful nonetheless

Helper method to easily tell if this policy is bound to a model

Returns:

  • (Boolean)

    True if this Policy is bound to a model, false otherwise


17
18
19
# File 'lib/scram/app/models/policy.rb', line 17

def model?
  return !model.nil?
end