Ruby(和Rails)嵌套模块语法 [英] Ruby (and Rails) nested module syntax

查看:62
本文介绍了Ruby(和Rails)嵌套模块语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道以下两个模块之间有什么区别

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

# First Example
module Parent
  module Child
  end
end

# Second Example
module Parent::Child
end

使用第二种方法时,似乎必须事先定义了Parent模块,否则会出现未初始化的常量"错误

Using the 2nd method, it appears as though the Parent module must be previously defined, otherwise I get an 'uninitialized constant' error

鉴于此,定义这样的模块然后添加关于语法和文件结构(例如文件夹等)的嵌套子级的首选方式是什么.引用Rails的方式将不胜感激.

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?

推荐答案

在第一个示例中,它定义了Parent模块,然后定义了Child模块.正如您自己说的那样,第二个示例必须事先定义了Parent模块.花费一行额外的代码,您可以确保始终使用第一个示例定义要嵌套的模块.

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.

以Rails为例,我们来看一下 railties/lib/rails/engine.rb 文件,该文件

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.

这篇关于Ruby(和Rails)嵌套模块语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆