简体   繁体   中英

Extending Modules in Rails

I have a folder within my lib folder that holds a module and some submodules. Simplified it looks like this:

Folder structure

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

Also, in config/application.rb I have the following line:

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:

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?

The problem is in the way Rails auto loads things I believe. 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). So the solution is to move the bottles.rb file up a directory level.

Rails expect different files structures, something like that:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM