Double Colon Ruby Class Naming Convention

I know that :: in Ruby is an access area resolution operator for accessing methods in modules and classes, but is it correct to rename classes with :: ?

Example

 class Foo::Bar::Bee < Foo::Bar::Insect def a_method [...] end end 
+2
source share
3 answers

If by "correct" you mean syntactically correct - yes .

There is nothing wrong with that, and if you define a subclass in a separate file (example below), then this is a relatively common practice.

 # lib/foo.rb module Foo end # lib/foo/bar.rb class Foo::Bar end 

I would not define classes this way if you cannot be sure that the parent module or class already exists, since you will get a NameError due to the lack of a parent (e.g. Foo ). For this reason, you will not see a lot of open source software that follows a shorter template.

Separately, this will not work:

 class Foo::Bar end 

This, however, will work:

 module Foo class Bar end end 
+2
source

Use is absolutely correct.

Just be careful in getting:

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

This will work fine:

 module Foo; end class Foo::Bar; end 
+1
source

Yes, this use is excellent. A format is just a way of referencing a constant; the expression solves one constant anyway.

0
source

All Articles