ruby-on-railsruby-on-rails-3current-pagepundit

Rails: defining policy with pundit that depends on which page the user is visiting


I have the same partial in rails that is required in two pages, that shows a list of posts. The first is a news feed page, the second is a "details" page.

In the first one the user shouldn't be able to edit, in the second he should be able to.

The partial is something like that:

<%= best_in_place_if policy(post).update?,
                     blahblah...
                     %>
<% end %>

The policy is implemented like that:

class PostPolicy < ApplicationPolicy
  include ActionView::Helpers::UrlHelper

  ...

  def update?
    ((@record.open? && not_blocked?) ||
    owner? ||
    collaborator?) &&
    !news_feed?
  end
  private

  def news_feed?
    current_page?(action: 'authenticated')
  end

  ...
end

But it seems that I can't access to method current_page?. Is there a way to know from policies what is the actual page I'm visiting?

Thank you


Solution

  • Another possible solution might be to do this:

    class PostPolicy < ApplicationPolicy
      # remove this: include ActionView::Helpers::UrlHelper
      ...
    
      def news_feed?
        ApplicationController.helpers.current_page?(action: 'authenticated')
      end
    
      ...
    end
    

    See this RailsCast and this Stackoverflow thread for more.