簡體   English   中英

在Rails中擴展模塊

[英]Extending Modules in Rails

我的lib文件夾中有一個文件夾,其中包含一個模塊和一些子模塊。 簡化后看起來像這樣:

資料夾結構

lib/bottles  
lib/bottles/bottles.rb  
lib/bottles/caps.rb  

Bottles.rb

module Bottles
  def hello_bottles
    puts "Hello Bottles"
  end
end

caps.rb

module Bottles
  module Caps
    def hello_caps
      puts "Hello Caps"
    end
  end
end

另外,在config/application.rb我有以下幾行:

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

我在類中包括該模塊及其子模塊,如下所示:

class MyClass
  extend Bottles
  extend Bottles::Caps
end

問題是,調用MyClass.hello_caps可以正常工作並顯示"Hello Caps" ,但是調用MyClass.hello_bottles給我一個未定義的方法錯誤:

NoMethodError: undefined method 'hello_bottles' for MyClass

擴展頂級Bottles模塊的正確語法和配置是什么,以便可以將其方法用作類方法?

問題在於Rails自動加載我相信的東西的方式。 因為它將在<load_path>/bottles.rb中的文件中查找頂層模塊,所以找不到它(這就是caps起作用的原因,因為它在目錄中查找與頂層同名的所有子模塊模塊)。 因此,解決方案是將Bottles.rb文件移至目錄級別。

Rails期望使用不同的文件結構,如下所示:

lib/bottles.rb  
lib/bottles/caps.rb

http://guides.rubyonrails.org/autoloading_and_reloading_constants.html#autoloading-algorithms-relative-references

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM