2015-07-01 12 views
14

Có đoạn mã sau:Guard khoản thay vì gói mã bên trong một biểu thức điều kiện 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 

tôi sử dụng Rubocop để kiểm tra mã của tôi nếu nó phù hợp với hướng dẫn của Ruby. Tôi đã nhận lỗi sau:

Use a guard clause instead of wrapping the code inside a conditional expression. 
    unless @user && @user.authenticate(params[:user][:password]) 

Vì vậy, tôi không hiểu làm thế nào tôi có thể làm cho mã này sử dụng tốt hơn điều khoản bảo vệ. Cảm ơn trước!

Trả lời

20

rubocops Sau spec: http://www.rubydoc.info/github/bbatsov/rubocop/Rubocop/Cop/Style/GuardClause

Cái gì đó như ...

return if @user && @user.authenticate(params[:user][:password]) 
@error_message = 'Invalid username or password' 
render 'shared/error', status: :unauthorized 
+0

Không tốt. Nếu người dùng && user.authenticate tôi cần hiển thị chế độ xem theo mặc định – malcoauri

+3

những gì osman đã làm ở trên tương đương với mã của bạn. nó sẽ vẫn hiển thị mẫu tạo khi người dùng xác thực thành công. – jvnill

Các vấn đề liên quan