Using Pundit in Phlex Components
Pundit provides a set of helpers to use in your views and controllers. These helpers are the primary way of interacting with Pundit policies.
All of the helper methods come from the Pundit::Authorization module. You're instructed to include this module in your ApplicationController when you install Pundit. This also make the helpers available in your vanilla ERB views. These view helpers methods can, for example, be used to conditionally render content. Here's an example from the Pundit README:
<% if policy(@post).update? %>
<%= link_to "Edit post", edit_post_path(@post) %>
<% end %>To use this technique in Phlex components, we need to include the Pundit::Authorization helper. However, this module also needs access to the currenlty authenticated user, so we need to tell it how to find that user. We do this the same way we did for our ApplicationController: by defining a pundit_user method.
If we're going to be doing authorization checks in many different views, it makes sense to include these in our Base view.
class Views::Base < Components::Base
include Pundit::Authorization
def pundit_user = Current.user # or another reference to the authenticated user
endapp/views/base.rb
Now our components have access to all of the Pundit helper methods, so we can do something like this in our Phlex view:
def render_edit_link
if policy(@post).update?
a(href: edit_post_path(@post)) { "Edit post" }
end
end