Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "::" instead of "module ..." for Ruby namespacing

In Ruby, is there a difference between writing class Foo::Bar and module Foo; class Bar for namespacing? If so, what?

like image 573
mybuddymichael Avatar asked Aug 03 '11 13:08

mybuddymichael


2 Answers

If you use class Foo::Bar, but the Foo module hasn't been defined yet, an exception will be raised, whereas the module Foo; class Bar method will define Foo if it hasn't been defined yet.

Also, with the block format, you could define multiple classes within:

module Foo
  class Bar; end
  class Baz; end
end
like image 78
Dylan Markow Avatar answered Sep 21 '22 15:09

Dylan Markow


Also notice this curious bit of Ruby-ismness:

FOO = 123

module Foo
  FOO = 555
end

module Foo
  class Bar
    def baz
      puts FOO
    end
  end
end

class Foo::Bar
  def glorf
    puts FOO
  end
end

puts Foo::Bar.new.baz    # -> 555
puts Foo::Bar.new.glorf  # -> 123
like image 36
Casper Avatar answered Sep 17 '22 15:09

Casper