Module: Consent::Authorizable

Extended by:
ActiveSupport::Concern
Defined in:
app/models/concerns/consent/authorizable.rb

Instance Method Summary collapse

Instance Method Details

#grant(subject:, action:, view:) ⇒ Object

Grants a permission to a role, replacing any existing permission for the same subject/action pair:

‘grant` only grants valid permissions:

‘grant` also does not persist the given permissions, so the caller must #save! the role

Examples:

role.grant(subject: "user", action: "read", view: "all")
role.grant(subject: "user", action: "read", view: "territory")
role.permissions
=> [#<Consent::Permission subject: User(...), action: :read, view: :territory>]
role.grant(subject: "user", action: "read", view: "no_access")
role.permissions
=> []

Parameters:

  • subject (Symbol|String|Class)

    any valid subject

  • action (String|Symbol)

    a valid action

  • view (String|Symbol)

    a valid view



76
77
78
# File 'app/models/concerns/consent/authorizable.rb', line 76

def grant(subject:, action:, view:)
  grant_permission ::Consent::Permission.new(subject: subject, action: action, view: view)
end

#grant_all(permissions, replace: false) ⇒ Object

Grants all permissions in o permissions hash formatted as:

‘{ <subject> => { <action> => <view> } }`

When ‘replace: true`, it mark all existing permisions for destruction

‘grant_all` will only keep valid permissions, this excludes any permisison that grants nothing (:no_access)

Examples:

role.grant_all({ “user” => { “read” => “all” }})

role.grant_all({ User => { read: :all }})

role.grant_all(User => { read: :territory })
role.grant_all({ User => { write: :territory }, replace: true)
role.permissions
=> [#<Consent::Permission subject: User(...), action: :write, view: :territory>]

Parameters:

  • permissions (Hash)

    a hash formatted as documented above

  • replace (Boolean) (defaults to: false)

    whether we should replace all existing granted permisions



33
34
35
36
37
38
# File 'app/models/concerns/consent/authorizable.rb', line 33

def grant_all(permissions, replace: false)
  changed = self.permissions
                .from_hash(permissions)
                .map { |permission| grant_permission(permission) }
  (self.permissions - changed).each(&:mark_for_destruction) if replace
end

#grant_all!(*args, **kwargs) { ... } ⇒ Object

Destructive form of #grant_all. This methods grants all the given permissions and persists it to the database atomically

Yields:

  • after saving before commiting within the transaction

See Also:



46
47
48
49
50
51
52
53
# File 'app/models/concerns/consent/authorizable.rb', line 46

def grant_all!(*args, **kwargs)
  transaction do
    grant_all(*args, **kwargs)
    tap(&:save!)
    touch
    yield if block_given?
  end
end