在Rails中扩展模块

时间:2015-10-01 10:04:59

标签: ruby-on-rails ruby ruby-on-rails-4 module

我的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模块的正确语法和配置是什么,以便我可以将其方法用作类方法?

2 个答案:

答案 0 :(得分:1)

问题在于Rails自动加载我相信的东西。因为它会在位于<load_path>/bottles.rb的文件中查找顶级模块,所以它找不到它(这就是为什么大写可以工作,因为它查找目录中与顶级模块同名的所有子模块) 。因此,解决方案是将bottles.rb文件移动到目录级别。

答案 1 :(得分:1)

Rails期望不同的文件结构,类似:

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

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

相关问题