重构和回调

时间:2014-07-21 20:22:07

标签: ruby-on-rails ruby

在一个控制器中,我得到了一个方法,我想重构与其他控制器共享。与此同时,我将其传递给回调before_action

应用/模型/ meal_controller.rb

def check_for_user
  token = request.headers[:token]
  if token.nil?
    render json: "Unathorized", status: 401
  elsif @meal.user.auth_code != token
    render json: "Forbidden", status: 403
  end 
end

所以我的方法是将check_for_user移动到ApplicationController并按如下方式修改它:

  def check_for_user(item)
    token = request.headers[:token]
    if token.nil?
        render json: "Unathorized", status: 401
    elsif item.user.auth_code != token
        render json: "Forbidden", status: 403
    end 
  end

回到MealController,创建另一个"虚拟"没有参数的方法并调用check_for_user。

def check_for_user_meal
  check_for_user(@meal)
end

我的问题是:有没有更好的方法来重构此代码?

提前致谢。

2 个答案:

答案 0 :(得分:3)

我的代码在ApplicationController中没有问题,如果它只有几行代码。

但是,我建议您查看the difference between 401 and 403。主要区别在于401表示您的身份验证尝试出错,请重试; 403表示您尝试以不正确的方式进行身份验证,请停止尝试。

使用用户名/密码用户输入,401是有意义的,因为用户可能错误输入了某些内容。

但是使用令牌,另一种尝试只会获得相同的结果。因此,没有令牌和错误的令牌都会导致403错误。

所以我会像这样重构你的代码:

def request_token
  request.headers[:token]
end

def check_for_user(item)
  if request_token.nil? || item.user.auth_code != request_token
    render json: "Forbidden", status: 403
  end
end 

答案 1 :(得分:0)

您可以创建一个模块,以便该方法可以在整个应用程序中使用。

相关问题