【发布时间】:2020-09-14 10:27:44
【问题描述】:
我有以下命名空间 ApiController
class Api::ApiController < ApplicationController
skip_before_action :verify_authenticity_token,
if: Proc.new { |c| c.request.content_type == 'application/json' }
before_action :authenticate
attr_reader :current_user
private
def authenticate
@current_user = AuthorizeApiRequest.call(request.headers).result
render json: { error: 'Not Authorized' }, status: 401 unless @current_user
end
end
在AuthorizeApiRequest.call,Rails 抱怨说:
未初始化的常量 Api::ApiController::AuthorizeApiRequest
我的 AuthorizeApiRequest 类在 app/commands 下定义:
class AuthorizeApiRequest
prepend SimpleCommand
def initialize(headers = {})
@headers = headers
end
def call
user
end
private
attr_reader :headers
def user
@user ||= User.find(decoded_auth_token[:user_id]) if decoded_auth_token
@user || errors.add(:token, 'Invalid token') && nil
end
def decoded_auth_token
@decoded_auth_token ||= JsonWebToken.decode(http_auth_header)
end
def http_auth_header
if headers['Authorization'].present?
return headers['Authorization'].split(' ').last
else
errors.add(:token, 'Missing token')
end
nil
end
end
所以它似乎不允许我在没有在前面添加命名空间的情况下调用AuthorizeApiRequest.call。如何解决?
【问题讨论】:
-
尝试使用
::AuthorizeApiRequest.call
标签: ruby-on-rails