简体   繁体   中英

Facing the NameError when trying to include concerns in my rails 6 controller

I am trying to create a small project for practising the API Key Authentication using the this tutorial. I have created a concern in following directory of the rails project.

app/controllers/concerns/api_key_authenticable.rb

module ApiKeyAuthenticatable
  extend ActiveSupport::Concern

  include ActionController::HttpAuthentication::Basic::ControllerMethods
  include ActionController::HttpAuthentication::Token::ControllerMethods

  attr_reader :current_api_key
  attr_reader :current_bearer

  # Use this to raise an error and automatically respond with a 401 HTTP status
  # code when API key authentication fails
  def authenticate_with_api_key!
    @current_bearer = authenticate_or_request_with_http_token &method(:authenticator)
  end

  # Use this for optional API key authentication
  def authenticate_with_api_key
    @current_bearer = authenticate_with_http_token &method(:authenticator)
  end

  private

  attr_writer :current_api_key
  attr_writer :current_bearer

  def authenticator(http_token, options)
    @current_api_key = ApiKey.find_by token: http_token

    current_api_key&.bearer
  end
end

In my Controller, I am trying to include the concern like this

app/controllers/ApiKeysController.rb

class ApiKeysController < ApplicationController
  include ApiKeyAuthenticatable 
 
  # Require token authentication for index                             
  prepend_before_action :authenticate_with_api_key!, only: [:index] 
 
  # Optional token authentication for logout                           
  prepend_before_action :authenticate_with_api_key, only: [:destroy] 
 
  def index
  end
 
  def create
  end
 
  def destroy
  end
end

But when I run the server and visit the index action of the controller, I get the following error

NameError (uninitialized constant ApiKeysController::ApiKeyAuthenticatable):
  
app/controllers/ApiKeysController.rb:10:in `<class:ApiKeysController>'
app/controllers/ApiKeysController.rb:2:in `<main>'

Can anybody help me out to fix this issue?

Author here. Your concern's filename is authenticable but your module is authenticatable . You'll need to correct the typo in the concern filename.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM