Reputation:
I have Module log_exception in lib folder as follows:
/lib/log_exception.rb
module LogException
def Log(e, message="")
Rails.logger.error "#{message}: #{e.message}"
e.backtrace[0..13].each {|line| Rails.logger.error line}
end
end
extend LogException
And now I am trying to use the Log method (which will be class method as module is extended) directly in this controller as:
Log(e, "Error in home action of DashboardController")
But it is giving me the following error:
undefined method `Log' for #<DashboardController
I have also set following in my application.rb
config.autoload_paths += %W(#{config.root}/lib)
If I extend same module in any of Model(User) and call the same method as
User.Log(e, "Error in home action of DashboardController")
then it is working fine, but not in case of controller.
I have tried various options but no luck.
Could anyone explains me what I am doing wrong? or How can I extend Module in controller?
Upvotes: 0
Views: 790
Reputation: 52347
You should include
, not extend
.
What extend
gives you is possibility to do
ControllerName.Log(...)
But what you really want, is to be able to use the method on the controller instances (since while being in the home
action you are actually operating on the controller instance), not on controller itself.
One more thing Can I access same method directly without doing include or extend on module? if yes can you please share?
module LogException
def Log(e, message="")
Rails.logger.error "#{message}: #{e.message}"
e.backtrace[0..13].each {|line| Rails.logger.error line}
end
extend self
end
LogException.Log(your_error, your_message)
Upvotes: 1