3

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?

1 Answer 1

1

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/.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm afraid there is no a.rb file, so this isn't the answer. Everything you need to replicate what I did in the Rails console is in the question (i.e., the folder 'a', with the file 'b.rb' as shown).
But the reason is the same, A::B is not loaded. You may want to read: guides.rubyonrails.org/autoloading_and_reloading_constants.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.