module Consent

Consent makes defining permissions easier by providing a clean, concise DSL for authorization so that all abilities do not have to be in your `Ability` class.

Constants

VERSION
ViewNotFound

Public Class Methods

default_views() click to toggle source

Default views available to every permission

i.e.:

Defining a view with no conditions:
Consent.default_views[:all] = Consent::View.new(:all, "All")

@return [Hash<Symbol,Consent::View>]

# File lib/consent.rb, line 24
def self.default_views
  @default_views ||= {}
end
define(key, label, options = {}, &block) click to toggle source

Defines a subject with the given key, label and options

i.e:

Consent.define :users, "User management" do
  view :department, "Same department only" do |user|
    { department_id: user.department_id }
  end
  action :read, "Can view users"
  action :update, "Can edit existing user", views: :department
end
# File lib/consent.rb, line 84
def self.define(key, label, options = {}, &block)
  defaults = options.fetch(:defaults, {})
  subjects << Subject.new(key, label).tap do |subject|
    DSL.build(subject, defaults, &block)
  end
end
find_action(subject_key, action_key) click to toggle source

Finds an action within a subject context

@return [Consent::Action,nil]

# File lib/consent.rb, line 47
def self.find_action(subject_key, action_key)
  find_subjects(subject_key)
    .flat_map(&:actions)
    .find do |action|
      action.key.eql?(action_key)
    end
end
find_subjects(subject_key) click to toggle source

Finds all subjects defined with the given key

@return [Array<Consent::Subject>]

# File lib/consent.rb, line 38
def self.find_subjects(subject_key)
  subjects.find_all do |subject|
    subject.key.eql?(subject_key)
  end
end
find_view(subject_key, action_key, view_key) click to toggle source

Finds a view within a subject context

@return [Consent::View,nil]

# File lib/consent.rb, line 58
def self.find_view(subject_key, action_key, view_key)
  find_action(subject_key, action_key)&.yield_self do |action|
    action.views[view_key] || raise(Consent::ViewNotFound)
  end
end
load_subjects!(paths, mechanism = :require) click to toggle source

Loads all permission (ruby) files from the given directory and using the given mechanism (default: :require)

@param paths [Array<String,#to_s>] paths where the ruby files are located @param mechanism [:require,:load] mechanism to load the files

# File lib/consent.rb, line 69
def self.load_subjects!(paths, mechanism = :require)
  permission_files = paths.map { |dir| File.join(dir, '*.rb') }
  Dir[*permission_files].each(&Kernel.method(mechanism))
end
subjects() click to toggle source

Subjects defined in Consent

@return [Array<Consent::Subject>]

# File lib/consent.rb, line 31
def self.subjects
  @subjects ||= []
end