shou2017.com
JP

RuboCop Complained: 'Use a guard clause instead of wrapping the code inside a conditional expression'

Thu Apr 18, 2019
Sat Aug 10, 2024

While working on the Rails Tutorial, RuboCop complained with: * RuboCop: Style/GuardClause: Use a guard clause instead of wrapping the code inside a conditional expression. [Style/GuardClause].

The code that triggered this warning was:

# Check if the user is logged in
def logged_in_user
  unless logged_in?
    flash[:danger] = "Please log in."
    redirect_to login_url
  end
end

It’s saying that the condition nesting is too deep and that I should use a guard clause instead.

After refactoring, it becomes:

# Check if the user is logged in
def logged_in_user
  return if logged_in?

  flash[:danger] = 'Please log in.'
  redirect_to login_url
end

I’m reviewing the Rails Tutorial with RuboCop for the first time, and I’m getting quite a few warnings. Why is that?

See Also