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

查看:27
本文介绍了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

使用第二种方法,看起来好像必须事先定义父模块,否则我会收到未初始化的常量"错误

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 文件,其中 重新打开Rails 模块,然后在其中定义了一个 Engine.这可以通过简单的方式完成:

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天全站免登陆