module Restrictable::ControllerMethods

Public Class Methods

only_allow(user_role, options={}) click to toggle source

Controller helper for denying access from user roles Example of use:

only_allow :admin, to: [:destroy, :edit, :update]
only_allow :seller, to: :destroy, fail: true
# File lib/restrictable.rb, line 32
def self.only_allow(user_role, options={})
  options[:only] = options[:to]
  should_fail = options[:fail] || false
  curated_options = options.except(:to, :fail)
  role = user_role.to_s

  before_action curated_options do |controller|
    if should_only_allow?(role)
      raise "You don't have access to this route or action" if should_fail
      controller.on_forbidden_action
    end
  end
end
prevent(user_role, options={}) click to toggle source

Controller helper for denying access from user roles Example of use:

prevent :seller, to: :destroy
prevent :supervisor, to: [:update, :edit, :delete, :destroy], fail: true
# File lib/restrictable.rb, line 14
def self.prevent(user_role, options={})
  options[:only] = options[:to]
  should_fail = options[:fail] || false
  curated_options = options.except(:to, :fail)
  role = user_role.to_s

  before_action curated_options do |controller|
    if should_prevent?(role)
      raise "You don't have access to this route or action" if should_fail
      controller.on_forbidden_action
    end
  end
end

Public Instance Methods

on_forbidden_action() click to toggle source
# File lib/restrictable.rb, line 46
def on_forbidden_action
  head :forbidden
end
should_only_allow?(role) click to toggle source
# File lib/restrictable.rb, line 58
def should_only_allow?(role)
  current_user.role != role
end
should_prevent?(role) click to toggle source
# File lib/restrictable.rb, line 50
def should_prevent?(role)
  if defined? User
    User.roles.keys.exclude?(role) || current_user.role == role
  else
    current_user.role == role
  end
end