Ruby (and Rails) nested module syntax

前端 未结 4 1863
梦如初夏
梦如初夏 2020-12-29 03:09

I\'m wondering what the difference is between the following two modules

# First Example
module Parent
  module Child
  end
end

and

4条回答
  •  再見小時候
    2020-12-29 04:01

    In the first example, it defines the Parent module and then the Child module. The second example, as you say yourself, must have the Parent module 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 Rails module and then defines an Engine class inside of it. This could have been done with simply:

    class Rails::Engine
    

    But instead perhaps for the reasons stated above and perhaps also for clarity's sake, the module was defined first, then the class inside.

提交回复
热议问题