双冒号在模块内部做什么?

时间:2013-11-11 01:10:59

标签: ruby module

我正在查看以下代码:

module Tag

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

我对标签模块中的::Tag感到困惑。

我知道双冒号用于命名空间类和类/模块中的模块。但我从来没有见过它像上面那样使用过。它究竟意味着什么?

1 个答案:

答案 0 :(得分:8)

这是一个范围修饰符。使用双冒号前缀常量(Tag)可确保您查看根/全局命名空间而不是当前模块。

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

前缀通常不是必需的,因为Ruby无法在本地模块中找到引用的常量,因此会自动查找全局命名空间。因此,如果Foo模块中不存在Bar,则Bar.greet::Bar.greet会执行完全相同的操作。

相关问题