Module: ActionSentinel::Permissible

Extended by:
ActiveSupport::Concern
Defined in:
lib/action_sentinel/permissible.rb

Overview

Provides methods for managing access permissions associated with a model.

This module is designed to be included in models that need to manage access permissions. It introduces methods for adding, removing, and checking permissions associated with a specific controller and actions.

Examples:

Including Permissible in a Model

class User < ApplicationRecord
  include ActionSentinel::Permissible
end

user = User.new
user.add_permissions_to(:create, :update, :users)
user.has_permission_to?(:create, :users) # => true

Instance Method Summary collapse

Instance Method Details

#add_permissions_to(*actions, controller_path) ⇒ Boolean

Add permissions to the access_permissions association for a specific controller.

Parameters:

  • actions (Array<Symbol, String>)

    The actions to add permissions for.

  • controller_path (String)

    The name of the controller.

Returns:

  • (Boolean)

    true if the permission was saved, false otherwise.



33
34
35
36
37
# File 'lib/action_sentinel/permissible.rb', line 33

def add_permissions_to(*actions, controller_path)
  permission = access_permissions.find_or_initialize_by(controller_path: controller_path)
  permission.assign_attributes(actions: (permission.actions + sanitize_actions_array(actions)).uniq)
  permission.save
end

#has_permission_to?(action, controller_path) ⇒ Boolean

Check if the model has permission to perform a specific action in a controller.

Parameters:

  • action (Symbol, String)

    The action to check permission for.

  • controller_path (String)

    The name of the controller.

Returns:

  • (Boolean)

    true if the model has permission, false otherwise.



57
58
59
60
61
62
63
64
65
66
67
# File 'lib/action_sentinel/permissible.rb', line 57

def has_permission_to?(action, controller_path)
  query = access_permissions.where(controller_path: controller_path)

  query = if %w[sqlite sqlite3].include? self.class.connection.adapter_name.downcase
            query.where("actions LIKE ?", "%#{action}%")
          else
            query.where(':action = ANY("access_permissions"."actions")', action: action)
          end

  query.exists?
end

#remove_permissions_to(*actions, controller_path) ⇒ Boolean?

Remove permissions from the access_permissions association for a specific controller.

Parameters:

  • actions (Array<Symbol, String>)

    The actions to remove permissions for.

  • controller_path (String)

    The name of the controller.

Returns:

  • (Boolean, nil)

    true if the permission was saved, false if it was not or nil if the permission was not found.



45
46
47
48
# File 'lib/action_sentinel/permissible.rb', line 45

def remove_permissions_to(*actions, controller_path)
  permission = access_permissions.find_by(controller_path: controller_path)
  permission&.update(actions: (permission.actions - sanitize_actions_array(actions)))
end