21

What is the correct way to use the guard clause in this sample?

def require_admin
  unless current_user && current_user.role == 'admin'
    flash[:error] = "You are not an admin"
    redirect_to root_path
  end        
end

I don't know where to put flash message when trying to rewrite using these https://github.com/bbatsov/ruby-style-guide#no-nested-conditionals conventions

wurde
  • 2,487
  • 2
  • 20
  • 39
Sasha
  • 323
  • 1
  • 2
  • 5

1 Answers1

37

You can use the return statement here. Essentially, there is no need for the method to continue if those conditions are met, so you can bail out early.

def require_admin
  return if current_user&.role == 'admin'

  flash[:error] = 'You are not an admin'
  redirect_to root_path
end
Justin
  • 4,922
  • 2
  • 27
  • 69
  • 2
    This is older, but I still thought I'd add a small suggestion to that return clause. Since we have the safe navigation operator in ruby, we can refactor that guard clause to `return if current_user&.role == 'admin'` which is even more succinct. – boyd Mar 04 '20 at 17:41