1

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?

Lee McAlilly
  • 9,084
  • 12
  • 60
  • 94

2 Answers2

2

BTW, you could do something like:

delegate *%w(admin? moderator?), to: :user

def user_artist?
  user == @artist.user
end

def update?
  admin? || moderator? || user_artist?
end

That seems pretty clean to me.

jvillian
  • 19,953
  • 5
  • 31
  • 44
1

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

Ursus
  • 29,643
  • 3
  • 33
  • 50