In my Rails project I want to get all modules that are nested inside the module A.
The file lib/assets/a/b.rb, consists of:
module A
module B
end
end
In the Rails console:
A.constants
=> []
A::B.class
=> Module
A.constants
=> [:B]
Why is the first line returning an empty array, and how do I get round the problem?
That's because how Rails autoloading works.
When you call A.constants Rails find A in the a.rb file and get you the constants defined there. As it seems you didn't define any constant there, it is the empty array.
When you call A::B.class Rails autoloading looks for A::B and load a/b.rb. So, next time you call A.constants it returns the constants defined in both a.rb and a/b.rb, as both files are now loaded. And that's why it returns B the second time.
So, you can not solve the problem. This is expected as it is caused by how the Rails autoloading works.
Also, you say that your models are in lib/assets/, but this makes no difference, as it would be the same if they were in models/.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With