2015-09-26 68 views
0

我的AuthenticatorService模块位于文件app/services/authenticator_service.rb中。Rails:模块的NoMethodError

这个模块是这样的:

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 

我目前在我的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是在命名空间V1,因为它位于app/controllers/v1/sessions_controller.rb但在这里,这不是问题。

问题是,当我拨打对应于SessionsController::sign_in的路由时,出现以下错误:undefined method 'authenticate_with_credentials' for AuthenticatorService:Module

我不明白为什么我在开发和生产环境得到这个错误有多个原因:

  • 当我添加调试信息,我可以看到AuthenticatorService从控制器加载和访问
  • 此外,当我展现在公众实例方法,authenticate_with_credentials在结果中列出(puts AuthenticatorService.public_instance_methods
  • 在我的测试,这个控制器测试,一切正常...

也许有人可以给我一些帮助。

回答

1

解决您的问题,您AuthenticatorService模块中添加

module_function :authenticate_with_credentials 

声明。

AuthenticatorService.public_instance_methods包含此方法,因为包含此模块的实例将使此方法可用。但AuthenticatorService本身不是一个实例。

+0

好!我也刚刚见过'def AuthenticatorService.authenticate_with_credentials'。 –

+0

@SimonNinon在这个tpp上有一个战利品http://apidock.com/ruby/Module/module_function – dimakura