Ruby class naming convention with double colon

我的未来我决定 提交于 2019-12-07 10:24:53

问题


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

回答1:


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



回答2:


The usage is perfectly valid.

Just be wary of the gotcha:

class Foo::Bar; end   #  uninitialized constant Foo (NameError)

This will work fine:

module Foo; end
class Foo::Bar; end



回答3:


Yes, that usage is perfectly valid. The format is simply a way to reference the constant; the expression resolves to a single constant all the same.



来源:https://stackoverflow.com/questions/21052539/ruby-class-naming-convention-with-double-colon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!