我試圖將我的Rails項目的一部分抽取到我的lib目錄中,但我無法解決如何正確鏈接文件。我的目錄結構是這樣的:在lib目錄中組織文件
lib/
eventable/
calendar.rb
helpers.rb
# Rest of rails directories/files
我需要eventable目錄config/application.rb
:
config.autoload_paths += %W(#{config.root}/lib #{config.root}/lib/eventable)
我的助手和日曆RB文件:
# helpers.rb
module Eventable
module Helpers
def calendar_for...
Calendar.new...
end
end
end
# calendar.rb
module Eventable
class Calendar
# methods defined here
end
end
我再混合我的常規Rails幫助器中的Eventable :: Helpers模塊,以便我可以在我的視圖中使用calendar_for
:
ActionView::Base.send :include, Eventable::Helpers
這最後一步似乎工作正常。然而,當我去到一個視圖這是使用這個幫手,我得到:
uninitialized constant Eventable::Helpers::Calendar
如果我改變我的助手,以便它試圖訪問Eventable::Calendar.new
代替然後我得到:
uninitialized constant Eventable::Calendar
當我有所有這些都放在一個文件中,這一切都很完美。那麼我怎麼才能正確地鏈接這些文件呢?
感謝此工作。你知道爲什麼這是必要的嗎?是否因爲自動加載無法以正確的順序加載它們?或者因爲我從視圖幫助程序使用Calendar類的事實不足以告訴Rails該類需要自動加載(即,它到達那裏時,它爲時已晚?) –
我不認爲它與訂單或傭工有關。問題來自Ruby。模塊的位置應該與目錄結構相匹配,但是當它們直接從子目錄中需要時,它會引發錯誤。看看這個:[Ruby需要的最佳實踐](http://devblog.vworkapp.com/post/910714976/best-practice-for-rubys-require)。 –