Skip to main content
 首页 » 编程设计

ruby-on-rails之保护子句而不是将代码包装在条件表达式中 Rails

2025年01月19日13shanyou

有以下代码:

# 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 

我使用 Rubocop 检查我的代码是否符合 Ruby 准则。我收到以下错误:
Use a guard clause instead of wrapping the code inside a conditional expression. 
    unless @user && @user.authenticate(params[:user][:password]) 

所以,我不明白如何使用保护子句使这段代码更好。提前致谢!

请您参考如下方法:

以下 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