I’m wondering what the difference is between the following two modules
# First Example
module Parent
module Child
end
end
and
# Second Example
module Parent::Child
end
Using the 2nd method, it appears as though the Parent module must be previously defined, otherwise I get an ‘uninitialized constant’ error
Given this, what is the preferred way of defining modules such as this and then adding nested children with regards to syntax and file structure (ie. folders etc). Reference to a Rails way would be greatly appreciated.
Are these two examples for all intents and purposes equivalent?
In the first example, it defines the
Parentmodule and then theChildmodule. The second example, as you say yourself, must have theParentmodule defined before hand. At the expense of one more line of code, you ensure that the module that you’re nesting under by using your first example is always going to be defined.For a Rails example let’s look into the railties/lib/rails/engine.rb file which re-opens the
Railsmodule and then defines anEngineclass inside of it. This could have been done with simply:But instead perhaps for the reasons stated above and perhaps also for clarity’s sake, the module was defined first, then the class inside.