有以下代码:
# 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
Run Code Online (Sandbox Code Playgroud)
我使用Rubocop检查我的代码是否符合Ruby指南.我收到以下错误:
Use a guard clause instead of wrapping the code inside a conditional expression.
unless @user && @user.authenticate(params[:user][:password])
Run Code Online (Sandbox Code Playgroud)
所以,我不明白如何使用guard子句更好地编写代码.提前致谢!
osm*_*man 32
遵循rubocops规范:https://www.rubydoc.info/gems/rubocop/RuboCop/Cop/Style/GuardClause
就像是...
return if @user && @user.authenticate(params[:user][:password])
@error_message = 'Invalid username or password'
render 'shared/error', status: :unauthorized
Run Code Online (Sandbox Code Playgroud)
编程中有一个方便的规则,名称是“eager return”,因此在这种情况下,此Guard clause instead of wrapping the code inside a conditional expression
警报意味着人们可能应该使用 eagerreturn
语句,而不是将代码包装在语句内(或任何其他条件if
语句内的代码块)if
)
所以最好这样声明:
def method_name
return unless something?
# some code logic here
end
Run Code Online (Sandbox Code Playgroud)
比这个...
def method_name
if something?
# some code logic here
end
end
Run Code Online (Sandbox Code Playgroud)
在编码中,我们总是寻求简单性和原子定义,而 eagerreturn
语句是紧凑代码的一种非常好的方法。