1

I have the following namespaces 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

On AuthorizeApiRequest.call, Rails complains that:

uninitialized constant Api::ApiController::AuthorizeApiRequest

My AuthorizeApiRequest class is defined under 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

So it seems to not allow me to call AuthorizeApiRequest.call without added namespace to front. How to fix?

1
  • Try doing it using ::AuthorizeApiRequest.call Commented Sep 14, 2020 at 10:29

1 Answer 1

0

Your app/commands folder doesn't seem to be loaded into Rails at boot.

You need to include your app/commands in your autoload paths for this to work or require the file manually in your controller.

See: https://guides.rubyonrails.org/autoloading_and_reloading_constants.html#autoload-paths

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.