Search code examples
ruby-on-railsrubyconditional-statementscontrol-flowpundit

How to write a Pundit policy with 3 or statements?


I have a Pundit policy that's working properly, but the way I've written it doesn't seem to be the "best" way to express this. It's a policy with three "or" statements. Here's the code:

def update?
  user.admin? or user.moderator? || user.id == @artist.user_id
end

What's another way I could write this? Or is this the best way to express this?


Solution

  • Two possible ways to: either

    def update?
      user.admin_or_moderator? || user == @artist.user
    end
    

    admin_or_moderator? is just to say, it could be even something like privileged? and implement this method in your User model. Or

    def update?
      %i(admin moderator).include?(user.role) || user == @artist.user
    end
    

    Here I'm guessing you have something like a role in your User model but that's the idea