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
An explanation of Ruby guard clauses how to use them as an alternative to nested if statements. TLDR; a guard clause is a premature return (early exit) that "guards" against the rest of your code from executing if it's not necessary (based on criteria you specify).
Guard clause is a good idea because it clearly indicates that current method is not interested in certain cases. When you clear up at the very beginning of the method that it doesn't deal with some cases (e.g. when some value is less than zero), then the rest of the method is pure implementation of its responsibility.
A guard clause is a piece of conditional logic that is placed at the beginning of a function that will return out of the function early on if certain conditions are not met. Guard clauses are simple to implement in any function that involves conditional logic, and they make functions shorter and cleaner.
The guard clause is a nifty pattern that provides a super-simple way to clean up your code. Their main function is to terminate a block of code early, which reduces indentation of your code and therefore makes your code much easier to read and reason about.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With