我正在看下面的代码:
module Tag
def sync_taggings_counter
::Tag.find_each do |t|
# block here
end
end
end
Run Code Online (Sandbox Code Playgroud)
而我::Tag对标签模块内部感到困惑.
我知道双冒号用于命名空间类和类/模块中的模块.但我从来没有见过它像上面那样使用过.这究竟是什么意思?
它是一个范围修饰符.Tag使用双冒号前缀constant()可确保您查看根/全局命名空间而不是当前模块.
例如
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
Run Code Online (Sandbox Code Playgroud)
如果Ruby无法在本地模块中找到引用的常量,那么前导通常不是必需的,因为Ruby会自动查找全局命名空间.所以,如果没有Bar的富模块中存在,然后Bar.greet和::Bar.greet会做同样的事情.
| 归档时间: |
|
| 查看次数: |
409 次 |
| 最近记录: |