这些 Ruby 命名空间约定之间有什么区别? [英] What's the difference between these Ruby namespace conventions?

查看:60
本文介绍了这些 Ruby 命名空间约定之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以 Module 可以在 Ruby 中使用以提供除了 mixin 之外的命名空间,如下所示:

So Module can be used in Ruby to provide namespacing in addition to mixins, as so:

module SomeNamespace
  class Animal

  end
end

animal = SomeNamespace::Animal.new

但我也看到了以下用法:

But I've also seen the following used:

module SomeNamespace
end

class SomeNamespace::Animal

end

animal = SomeNamespace::Animal.new

我的问题是它们有什么不同(如果有的话),哪个更符合地道的 Ruby?

My question is how they're different (if they are) and which is more idiomatic Ruby?

推荐答案

区别在于嵌套.

在下面的例子中,你可以看到前一个方法使用类Foo,可以无误地获取外部作用域的常量变量BAR_A.

In the example below, you can see that the former method using class Foo, can get the outer scope's constant variables BAR_A without errors.

与此同时,Baz 类会因未初始化的常量 A::B::Baz::BAR_A 的错误而爆炸.因为它没有隐式引入 A::*,只有 A::B::* 显式引入.

Meanwhile, class Baz will bomb with an error of uninitialized constant A::B::Baz::BAR_A. As it doesn't bring in A::* implicitly, only A::B::*explicitly.

module A
  BAR_A = 'Bar A!'
  module B
    BAR_B = 'Bar B!'
      class Foo
        p BAR_A
        p BAR_B
      end
  end
end

class A::B::Baz
  p BAR_A
  p BAR_B
end

这两种行为各有千秋.在我看来,社区中没有真正的共识,即 One True Ruby Way (tm).我个人大部分时间使用前者.

Both behaviors have their place. There's no real consensus in the community in my opinion as to which is the One True Ruby Way (tm). I personally use the former, most of the time.

这篇关于这些 Ruby 命名空间约定之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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