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