Class: Lolita::Extensions::Authorization::PunditAdapter

Inherits:
Object
  • Object
show all
Defined in:
lib/lolita/extensions/authorization/pundit_adapter.rb

Instance Method Summary collapse

Constructor Details

#initialize(context, options = {}) ⇒ PunditAdapter

Returns a new instance of PunditAdapter.

Raises:

  • (NameError)


6
7
8
9
10
11
12
# File 'lib/lolita/extensions/authorization/pundit_adapter.rb', line 6

def initialize context, options={}
  raise NameError, "Pundit is not defined" unless defined?(Pundit)
  raise Lolita::NoAuthorizationDefinedError, "Lolita.authorization is not defined" unless Lolita.authorization
  @context = context
  @options = options
  current_ability
end

Instance Method Details

#authorize!(*args) ⇒ Object



30
31
32
33
34
35
# File 'lib/lolita/extensions/authorization/pundit_adapter.rb', line 30

def authorize! *args
  unless ability = current_ability(*args) and ability.public_send(policy_method(args))
    raise Pundit::NotAuthorizedError.new("not allowed to #{args.first} this #{args.last}")
  end
  true
end

#can?(*args) ⇒ Boolean

Returns:

  • (Boolean)


14
15
16
# File 'lib/lolita/extensions/authorization/pundit_adapter.rb', line 14

def can? *args
  !!(ability = current_ability(*args) and ability.send(policy_method(args)))
end

#cannot?(*args) ⇒ Boolean

Returns:

  • (Boolean)


18
19
20
# File 'lib/lolita/extensions/authorization/pundit_adapter.rb', line 18

def cannot? *args
  !can?(*args)
end

#current_ability(*args) ⇒ Object



22
23
24
25
26
27
28
# File 'lib/lolita/extensions/authorization/pundit_adapter.rb', line 22

def current_ability *args
  if current_user && record = get_record(*args)
    @current_ability = Pundit.policy(current_user, record) || Lolita.policy_class.new(current_user, record)
    @context && @context.instance_variable_set(:"@current_ability", @current_ability)
  end
  @current_ability
end