varvet / pundit

Minimal authorization through OO design and pure Ruby classes
MIT License
8.31k stars 633 forks source link

Add policy_class on policy method #630

Closed JayFischer closed 5 years ago

JayFischer commented 5 years ago

When using the policy method to get an policy instance, we are only allow to pass a record. The PolicyFinder will take care of the instantiated record policy, but what if policy class needs to be overridden?

https://github.com/varvet/pundit/blob/9bd0f71ce8efc6645ce3166978e65d73092de8ab/lib/pundit.rb#L260-L262

Question or Enhancement?

Can we extend the policy method to act more similar to the authorize method with policy_class arg? Or maybe there is a preferred way of doing this?

Example:

<% if policy(@post, policy_class: RandomPostPolicy).update? %>
  <%= link_to "Edit post", edit_post_path(@post) %>
<% end %>

Otherwise, just instantiate the needed policy or wrap/override pundits policy method?

<% if RandomPostPolicy.new(current_user, @post).update? %>
  <%= link_to "Edit post", edit_post_path(@post) %>
<% end %>

Not sure if the change would be worth it or if theres a preferred way of handling. Happy to make a PR if supported.

Linuus commented 5 years ago

I don’t see any need for it if you already know what policy you want anyway. Just instantiate it. :)

It’s useful for authorize since it’s doing some other things as well, like marking as authorized for instance.

fydelio commented 4 years ago

I agree with Jay, of course you can instatiate it, but its not consistent with the authorize method. As the profect groes you might sometimes have nested routes, where you want to authorize the parent, but want the child policy to handle it