module Zobi::ControlledAccess

This module help to manage control access on your collection using pundit.

Public Class Methods

included(base) click to toggle source
# File lib/zobi/controlled_access.rb, line 8
def self.included base
  base.send :include, Pundit
  base.class_eval do
    before_action :authorize_resource

    def policy_scope scope
      Pundit.policy_scope!(controlled_access_user, scope)
    end

    def policy record
      Pundit.policy!(controlled_access_user, record)
    end
  end
end

Public Instance Methods

policy(record) click to toggle source
# File lib/zobi/controlled_access.rb, line 17
def policy record
  Pundit.policy!(controlled_access_user, record)
end
policy_scope(scope) click to toggle source
# File lib/zobi/controlled_access.rb, line 13
def policy_scope scope
  Pundit.policy_scope!(controlled_access_user, scope)
end

Protected Instance Methods

authorize_resource() click to toggle source

Authorize resource, see Policies.

# File lib/zobi/controlled_access.rb, line 26
def authorize_resource
  case action_name
  when build_resources_authorized
    authorize controlled_access_build_resource
  when resources_authorized
    authorize controlled_access_resource
  else
    authorize zobi_resource_class
  end
end
controlled_access_user() click to toggle source
# File lib/zobi/controlled_access.rb, line 37
def controlled_access_user
  if self.class.to_s.split('::').first == 'Admin'
    begin
      current_administrator
    rescue NameError
      raise "You need to define the current_administrator method.".inspect
    end
  else
    begin
      current_user
    rescue NameError
      raise "You need to define the current_user method.".inspect
    end
  end
end

Private Instance Methods

build_resources_authorized() click to toggle source
# File lib/zobi/controlled_access.rb, line 59
def build_resources_authorized
  /new|create/
end
controlled_access_build_resource() click to toggle source
# File lib/zobi/controlled_access.rb, line 67
def controlled_access_build_resource
  return build_resource if self.methods.include?(:build_resource)
  zobi_resource_class.new params[zobi_resource_class.to_s.to_sym]
end
controlled_access_collection(c) click to toggle source
# File lib/zobi/controlled_access.rb, line 55
def controlled_access_collection c
  policy_scope c
end
controlled_access_resource() click to toggle source
# File lib/zobi/controlled_access.rb, line 72
def controlled_access_resource
  return resource if self.methods.include?(:resource)
  zobi_resource_class.find(params[:id])
end
resources_authorized() click to toggle source
# File lib/zobi/controlled_access.rb, line 63
def resources_authorized
  /edit|update|show|destroy/
end