0

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:

  • When I add debug information, I can see that the AuthenticatorService is loaded and accessible from the controller
  • Moreover, when I display the public instance methods, authenticate_with_credentials is listed in the result (puts AuthenticatorService.public_instance_methods)
  • In my test, this controller is tested and everything works as expected...

Maybe someone could give me some help.

1 Answer 1

1

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.

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

2 Comments

Good! I've also just seen def AuthenticatorService.authenticate_with_credentials.
@SimonNinon have a loot at this tpp apidock.com/ruby/Module/module_function

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.