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!
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
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