Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly use guard clause in Ruby

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

like image 738
Sasha Avatar asked Aug 11 '15 13:08

Sasha


People also ask

How do you use the guard clause in Ruby?

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).

When to use guard clause?

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.

What is guard clause in Javascript?

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.

What is guard clause in Python?

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.


1 Answers

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
like image 136
Justin Avatar answered Sep 25 '22 11:09

Justin