varvet / pundit

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

`can? :create, Method` #695

Closed dorianmariecom closed 2 years ago

dorianmariecom commented 2 years ago

I have this in my application_helper.rb which I find quite helpful, maybe others can benefit from it?

  def can?(action, record)
    policy(record).public_send("#{action}?")
  end

It's kinda inspired by cancan(can) and allows to do things like:

can? :create, User
can? :update, @event
can? :show, :attendance
dorianmariecom commented 2 years ago

I also have that for inside my policies:

    def can?(action, record)
      policy(record).public_send("#{action}?")
    end

    def policy(record)
      if record.is_a?(String) || record.is_a?(Symbol)
        "#{record.to_s.camelize}Policy".constantize.new(user, record)
      else
        "#{record.class}Policy".constantize.new(user, record)
      end
    end

that's more hacky though

dgmstuart commented 2 years ago

Thanks for the suggestion - this is neat, but it doesn't feel like something we'd want to include in the project.