带有双冒号的 Ruby 类命名约定 [英] Ruby class naming convention with double colon
问题描述
我知道 Ruby 中的 ::
是一个作用域解析操作符,用于访问模块和类中的方法,但是使用 ::
命名类是否合适?>
示例
class Foo::Bar::Bee <Foo::Bar::昆虫def a_method[...]结尾结尾
如果正确"是指语法正确 - 是.
这样做并没有什么本质上的错误,如果您在单独的文件中定义子类(下面的示例),那么这是一种相对常见的做法.
# lib/foo.rb模块 Foo结尾# lib/foo/bar.rb类 Foo::Bar结尾
如果您不能确定父模块或类是否已经存在,我会避免以这种方式定义类,因为由于父模块(例如 Foo
) 不存在.出于这个原因,您不会看到很多遵循更简洁模式的开源软件.
孤立地,这行不通:
class Foo::Bar结尾
然而,这会起作用:
模块 Foo班级酒吧结尾结尾
I know the ::
in Ruby is a scope resolution operator to access methods within modules and classes, but is it proper to name classes using ::
?
Example
class Foo::Bar::Bee < Foo::Bar::Insect
def a_method
[...]
end
end
If by "proper" you mean syntactically correct — yes.
There's nothing inherently wrong with doing it, and if you're defining a subclass in a separate file (example below) then it's a relatively common practice.
# lib/foo.rb
module Foo
end
# lib/foo/bar.rb
class Foo::Bar
end
I would avoid defining classes this way if you cannot be sure that the parent module or class already exists, though, as you'll get a NameError
due to the parent (e.g. Foo
) not existing. For this reason, you won't see much open source software that follows the more terse pattern.
In isolation, this will not work:
class Foo::Bar
end
This, however, would work:
module Foo
class Bar
end
end
这篇关于带有双冒号的 Ruby 类命名约定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!