Simon Ninon
Simon Ninon

Reputation: 2451

Rails: NoMethodError for module

I've an AuthenticatorService module located in the file app/services/authenticator_service.rb.

This module looks like this:

module AuthenticatorService

  # authenticate user with its email and password
  # in case of success, return signed in user
  # otherwise, throw an exception
  def authenticate_with_credentials(email, password)
    user = User.find_by_email(email)
    raise "Invalid email or password" if user.nil? or not user.authenticate password

    return user
  end

  # some other methods...

end

I currently use this module in my SessionsController.

class V1::SessionsController < ApplicationController
  # POST /sessions
  # if the credentials are valid, sign in the user and return the auth token
  # otherwise, return json data containing the error
  def sign_in
    begin
      user = AuthenticatorService.authenticate_with_credentials params[:email], params[:password]
      token = AuthenticatorService::generate_token user

      render json: { success: true, user: user.as_json(only: [:id, :first_name, :last_name, :email]), token: token }
    rescue Exception => e
      render json: { success: false, message: e.message }, status: 401
    end
  end
end

SessionsController is in the namespace V1 because it is located in app/controllers/v1/sessions_controller.rb but that's not the problem here.

The problem is that, when I call the route corresponding to SessionsController::sign_in, I go the following error: undefined method 'authenticate_with_credentials' for AuthenticatorService:Module.

I can't understand why I get this error in development and production environments for multiple reasons:

Maybe someone could give me some help.

Upvotes: 0

Views: 249

Answers (1)

dimakura
dimakura

Reputation: 7655

To fix your problem, add

module_function :authenticate_with_credentials

declaration in your AuthenticatorService module.

AuthenticatorService.public_instance_methods contains this method, because instances which include this module will have this method available. But AuthenticatorService itself is not an instance.

Upvotes: 1

Related Questions