Guard子句而不是将代码包装在条件表达式Rails中

mal*_*uri 23 ruby-on-rails

有以下代码:

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

  • osman在上面做了什么等同于你的代码.当用户成功进行身份验证时,它仍会呈现创建模板. (4认同)

d1j*_*i1b 7

编程中有一个方便的规则,名称是“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语句是紧凑代码的一种非常好的方法。