Module: PunditHelpers

Defined in:
lib/pundit_helpers.rb,
lib/pundit_helpers/version.rb

Constant Summary collapse

VERSION =
"0.0.2"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
# File 'lib/pundit_helpers.rb', line 4

def self.included(base)
  methods = [:authorized?, :can?]

  if base.respond_to?(:helper_method)
    methods.each { |m| base.helper_method(m) }
  end

  if respond_to?(:hide_action)
    methods.each { |m| base.hide_action(m) }
  end
end

Instance Method Details

#authorized?(record, query = nil) ⇒ Boolean

Pundit’s core ‘#authorize` helper always raises an error, but also lets the controller know an authorization has been performed. Sometimes it is preferrable to flag that an authorization check has been made, but return boolean rather than raise. So this uses an exception rescue for flow control, which is not optimal but fits nicely with the current API and doesn’t cause serious breakage

Parameters:

  • record (record)
    • the record to check

  • query (string or symbol) (defaults to: nil)
    • the policy action to check for

Returns:

  • (Boolean)


27
28
29
30
31
32
33
# File 'lib/pundit_helpers.rb', line 27

def authorized?(record, query=nil)
  begin
    authorize(record, query)
  rescue Pundit::NotAuthorizedError
    false
  end
end

#can?(query, record) ⇒ Boolean

The current user permissions can be policy checked in views:

<% if can? :edit, @lesson %>

<a href="/posts/42/edit">edit</a>

<% end %>

Parameters:

  • query (string or symbol)
    • the query to check

  • record (record)
    • the record for policy lookup

Returns:

  • (Boolean)


45
46
47
48
49
# File 'lib/pundit_helpers.rb', line 45

def can?(query, record)
  query  = "#{query}?"
  policy = Pundit.policy!(current_user, record)
  !! policy.public_send(query)
end