0

I need to call Pundit authorization in a Rails Presenter.

I included Pundit so I can call policy function. But Pundit does not know current_user. (Rails 6 / Devise / Pundit)

Is there a way to do this ?

app/presenter/cause_presenter.rb

class CausePresenter < BasePresenter
  include Pundit
  
  def cause_tree_line
    # Here I want to call policy or authorize
  end
end

Result :

NameError (undefined local variable or method `current_user' for #<Tools::CausePresenter:0x00007f3f408b2050>

Thanks for your help.

LiKaZ
  • 306
  • 3
  • 9
  • I have no idea of the implementation of your presenter but I think you really want to pass a Pundit policy into the presenter instead of going bonkers trying to get pundits controller helpers to work in a context they where never designed for. – max Feb 02 '21 at 23:52
  • @max Thaks, maybe you can clarify something for me : We can use policy in views so why not in Presenters (or Decorators) ? This presenter adds links to an element. The links depend of user's role witch is managed in Pundit policy. In my view I can write `link_to 'destroy', [...] if policy(cause).destroy?` I wanted to do something similar in my Presenter, but maybe it is not the good place to do it. – LiKaZ Feb 04 '21 at 16:23
  • 1
    What I do is I pass the `current_user` instead to the presenter, e.g. `def cause_tree_line(current_user)` then in the body of `cause_tree_line` will be: `CausePolicy.new(current_user, cause).destroy?` or you can pass in `current_user` instead while still in the controller action, e.g. `@presenter = CausePresenter.new(cause, current_user)`, then use @current_user in `cause_tree_line` with the policy instantiation – puerile Jul 25 '21 at 22:34

0 Answers0