3

I'm looking at the following code:

module Tag

  def sync_taggings_counter
    ::Tag.find_each do |t|
       # block here
    end
  end
end

and I'm confused by ::Tag inside the Tag module.

I know the double colon is used to name-space classes and modules within classes/modules. But I've never seen it used like the above. What does it mean exactly?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
User314159
  • 7,733
  • 9
  • 39
  • 63
  • I wasn't right. Take a look at this question: http://stackoverflow.com/questions/3009477/what-is-rubys-double-colon-all-about – Paulo Bu Nov 11 '13 at 01:22

1 Answers1

9

It's a scope modifier. Prefixing your constant (Tag) with a double colon ensures that you're looking in the root/global namespace instead of within your current module.

E.g.

module Foo
  class Bar
    def self.greet
      "Hello from the Foo::Bar class"
    end
  end

  class Baz
    def self.scope_test
      Bar.greet # Resolves to the Bar class within the Foo module.
      ::Bar.greet # Resolves to the global Bar class.
    end
  end
end

class Bar
  def self.greet
    "Hello from the Bar class"
  end
end

The prepending is usually not neccessary as Ruby automatically looks in the global namespace, if it fails to find the referenced constant in the local module. So if no Bar existed in the Foo module, then Bar.greet and ::Bar.greet would do the exact same thing.

Niels B.
  • 5,912
  • 3
  • 24
  • 44