I am running a data extract with delayed_job that uses existing .html_erb templates that contain Pundit authorisations for example:
<%if policy(client).view_contacts? %>
Normally Pundit will look for a 'current_user' method in the controller to setup the Pundit policy class. However I have no controller as the job is being run from an ActiveJob using an instance of ActionView::Base to do the rendering.
I can change all the policy calls to be of the form:
<%if ClientPolicy.new(my_current_user,client).view_contacts? %>
However I would prefer to have a 'current_user' method that would be found by Pundit
I solved this by dynamically including Pundit and adding an attr_accessor for current_user to the version of ActionView::Base that is doing the rendering.
@av = ActionView::Base.new(Rails.root.join('app', 'views'))
@av.class_eval do
include ApplicationHelper
include Pundit
attr_accessor :current_user #for pundit
end
@av.current_user=@user
Now when the policy(client) method is called from the view it uses the attr_accessor to get the current user.