Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does a double colon do inside a module? [duplicate]

Tags:

module

ruby

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?

like image 738
User314159 Avatar asked Apr 10 '26 12:04

User314159


1 Answers

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.

like image 123
Niels B. Avatar answered Apr 13 '26 12:04

Niels B.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!