我的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
) - 在我的測試,這個控制器測試,一切正常...
也許有人可以給我一些幫助。
好!我也剛剛見過'def AuthenticatorService.authenticate_with_credentials'。 –
@SimonNinon在這個tpp上有一個戰利品http://apidock.com/ruby/Module/module_function – dimakura