Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guard clause instead of wrapping the code inside a conditional expression Rails

There is the following code:

# API controller for authentication class Api::V1::SessionsController < Api::V1::ApplicationController   skip_before_action :authorize    def create     @user = User.find_by(email: params[:user][:email])     unless @user && @user.authenticate(params[:user][:password])       @error_message = 'Invalid username or password'       render 'shared/error', status: :unauthorized     end   end end 

I use Rubocop to check my code if it matches to Ruby guidelines. I got the following error:

Use a guard clause instead of wrapping the code inside a conditional expression.     unless @user && @user.authenticate(params[:user][:password]) 

So, I don't understand how I can make this code better using guard clause. Thanks in advance!

like image 873
malcoauri Avatar asked Jul 01 '15 06:07

malcoauri


People also ask

What is a guard clause in Ruby?

Jul 27, 2019· 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). Soon after I started my career as a Ruby on Rails developer I learned about guard clauses and how they can improve code readability.

What is guard clause in Java?

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.


2 Answers

Following rubocops spec : https://www.rubydoc.info/gems/rubocop/RuboCop/Cop/Style/GuardClause

Something like...

return if @user && @user.authenticate(params[:user][:password]) @error_message = 'Invalid username or password' render 'shared/error', status: :unauthorized 
like image 129
osman Avatar answered Oct 06 '22 23:10

osman


There is a handy rule in programming, the name is "eager return" so in this case what this Guard clause instead of wrapping the code inside a conditional expression alert means is that One should be probably using an eager return statement instead of wrapping code inside an if statement (block of code inside an if or any other conditional)

So it is better to declare this:

  def method_name     return unless something?     # some code logic here   end 

Than this...

def method_name   if something?     # some code logic here   end end 

In coding we are always looking for simplicity and atomic definitions and eager return statements are a really nice way to tight up the code.

like image 36
d1jhoni1b Avatar answered Oct 06 '22 21:10

d1jhoni1b