在单独的文件中定义时,将Ruby类添加到模块中 [英] Add Ruby classes to a module when defined in separate files

查看:107
本文介绍了在单独的文件中定义时,将Ruby类添加到模块中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过将我的Ruby类放在模块中来命名它们的名称空间.的确,如果我决定发布我的Ruby gem,以使类名与另一个gem中的现有类不冲突,那么这是一个好主意.我知道我可以对A::B类执行以下操作:

I would like to namespace my Ruby classes by putting them in a module. Indeed, this is a good idea if I decide to publish my Ruby gem so that the class names do not clash with existing classes in another gem. I know I can do the following for a class A::B:

module A
  class B

  end
end

但是,以上内容非常麻烦,因为我需要将所有类定义放入单个Ruby源文件中,以便将其范围限定在模块下.我宁愿将类定义保存在单独的源文件中,就像Java项目一样,因此,当类都定义在单独的文件中时,如何将类添加到模块中呢?

However, the above is quite cumbersome in that I need to put all my class definitions into a single Ruby source file in order to scope them under the module. I would rather keep my class definitions in separate source files, much like a Java project, so how can I add classes to a module when they are all defined in separate files?

推荐答案

在这种情况下,可接受的做法是将每个文件包装在module块中

The accepted practice in this case is to wrap every file in module block

# a/b.rb
module A
  class B

  end
end

# a/c.rb
module A
  class C

  end
end

顺便说一句.由于解析常量的方式,建议使用我上面引用的长格式代替class A::B

Btw. because of the way constant are resolved, it is advisable to use the long form I quoted above instead class A::B

( http://blog.honeybadger.io/在嵌套红宝石模块时避免这些陷阱/).

这篇关于在单独的文件中定义时,将Ruby类添加到模块中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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