[英]Extending Modules in Rails
I have a folder within my lib
folder that holds a module and some submodules. 我的lib
文件夹中有一个文件夹,其中包含一个模块和一些子模块。 Simplified it looks like this: 简化后看起来像这样:
Folder structure 资料夹结构
lib/bottles
lib/bottles/bottles.rb
lib/bottles/caps.rb
bottles.rb Bottles.rb
module Bottles
def hello_bottles
puts "Hello Bottles"
end
end
caps.rb caps.rb
module Bottles
module Caps
def hello_caps
puts "Hello Caps"
end
end
end
Also, in config/application.rb
I have the following line: 另外,在config/application.rb
我有以下几行:
config.autoload_paths += %W(#{config.root}/lib)
I include the module and it's submodules in my class like so: 我在类中包括该模块及其子模块,如下所示:
class MyClass
extend Bottles
extend Bottles::Caps
end
The problem is that calling MyClass.hello_caps
works just fine and prints "Hello Caps"
, but calling MyClass.hello_bottles
gives me an undefined method error: 问题是,调用MyClass.hello_caps
可以正常工作并显示"Hello Caps"
,但是调用MyClass.hello_bottles
给我一个未定义的方法错误:
NoMethodError: undefined method 'hello_bottles' for MyClass
What is the correct syntax and configuration for extending the top level Bottles
module so I can use its methods as class methods? 扩展顶级Bottles
模块的正确语法和配置是什么,以便可以将其方法用作类方法?
The problem is in the way Rails auto loads things I believe. 问题在于Rails自动加载我相信的东西的方式。 Because it will look for the top level module in a file located in <load_path>/bottles.rb
it is not finding it (this is why caps works, because it looks for all submodules inside the directory with the same name as the top level module). 因为它将在<load_path>/bottles.rb
中的文件中查找顶层模块,所以找不到它(这就是caps起作用的原因,因为它在目录中查找与顶层同名的所有子模块模块)。 So the solution is to move the bottles.rb file up a directory level. 因此,解决方案是将Bottles.rb文件移至目录级别。
Rails expect different files structures, something like that: Rails期望使用不同的文件结构,如下所示:
lib/bottles.rb
lib/bottles/caps.rb
http://guides.rubyonrails.org/autoloading_and_reloading_constants.html#autoloading-algorithms-relative-references http://guides.rubyonrails.org/autoloading_and_reloading_constants.html#autoloading-algorithms-relative-references
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.