2015-09-26 64 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