2017-02-23 38 views
0

我在lib文件夹模块log_exception如下:Ruby on Rails的 - 扩展模块在控制器

/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 

,现在我尝试使用Log方法(这将类方法,如模块是扩展)直接在此控制器:

Log(e, "Error in home action of DashboardController") 

但它给我以下错误:

undefined method `Log' for #<DashboardController 

我还设置以下在我的application.rb中

config.autoload_paths += %W(#{config.root}/lib) 

如果我在延伸任何模型(用户)的相同模块,并调用相同的方法,

User.Log(e, "Error in home action of DashboardController") 

那么它是工作正常,但不是在控制器的情况下。

我已经尝试了各种选择,但没有运气。

任何人都可以解释我做错了什么吗?或者我如何在控制器中扩展模块?

回答

2

您应该include而不是extend

什么extend给你的可能性做

ControllerName.Log(...) 

但是你真正想要的,是能够使用的控制器实例的方法(因为同时在home行动是你实际操作上控制器实例),而不是控制器本身。

编辑:

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) 
+0

谢谢清除的东西,它的工作。 – Tushar

+0

@Tushar没有probs,确保接受答案,因为它解决了问题。 –

+0

接受你的回答,还有一件事我可以直接访问相同的方法,而无需在模块中包含或扩展?如果是,你可以分享吗? – Tushar