5

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
Ode
  • 549
  • 6
  • 19

3 Answers3

5

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
coreyward
  • 77,547
  • 20
  • 137
  • 166
  • What if the second constant in that name does not correlate to any sub module or class? For example the inherited class `Foo::Bar::Insect` Bar is not actually a sub module or class? – Ode Jan 10 '14 at 19:21
  • To be clear, I don't mean an inherited subclass, I mean a namespaced class or module, in which case it isn't `Foo::Bar`, it's just `Bar`. – coreyward Jan 10 '14 at 19:23
1

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
Denis de Bernardy
  • 75,850
  • 13
  • 131
  • 154
0

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.

Peter Alfvin
  • 28,599
  • 8
  • 68
  • 106