Home > OS >  Can I create namespace without putting file inside folder structure?
Can I create namespace without putting file inside folder structure?

Time:08-08

I have foo.rb file inside a lib directory. Can I do something like this

module A
  module B
    class Foo
    end
  end
end

I don't want to create folder inside lib directory like this lib/A/B/foo.rb. I just want to place file inside lib directory like this lib/foo.rb. Is this possible in Rails? I am getting uninitialized constant A (NameError) when trying to create new object like this A::B::Foo.new

I am able to create object if i copy/paste above code directly into rails console. But if write that code inside lib/foo.rb file then I am not able to create new object.

Upadate

I already have lib directory in autoload path

config.autoload_paths << Rails.root.join('lib')

CodePudding user response:

You have three options:

  1. Put code in lib/a/b/foo.rb which is how Rails conventions go. Rails autoloader will find the class there.
  2. Put the code in lib/a.rb so when autoloader looks for the namespace A it will load it, find the class you're referencing.
  3. Manually require lib/foo.rb in every place you're referencing it.

I don't know why anyone would pick option 3 but you're free to ignore Rails conventions and do your own thing. Your life will be much easier however if you follow the convention.

  • Related