2017-02-23 37 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