Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby class naming convention with double colon

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
like image 525
Ode Avatar asked Jan 10 '14 19:01

Ode


1 Answers

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
like image 135
coreyward Avatar answered Oct 28 '22 01:10

coreyward