class 开头的“::”如何影响范围 (ruby/rails)?

How does '::' at the beginning of the class affect scope (ruby/rails)?

我在一个大型 rails 项目中工作,我有一些文件:

app/services/my_service/my_action/my_model_2.rb:

module <my_service>
  module <my_action>
    class <my_model_2>
      . . .
      if some_var = <my_model>::MY_CONST
      if some_Var = ::<my_model>::MY_CONST # <-- what is the difference here?

app/services/my_service/my_action/my_model.rb:

module <my_service>
  module <my_action>
    class <my_model>

app/services/my_service/my_model.rb:

module <my_service>
    class <my_model>

app/models/my_model.rb:

class <my_model> < ActiveRecord::Base
  . . . 
  MY_CONST = "my constant"

my_model_2.rb有什么区别?

我如何才能正确地访问 my_model_2.rb 中的每个模型?

注意 app/models class 名称与 app/services class 名称相同。

前导 :: 强制 Ruby 解释器开始从顶级名称空间解析 class 名称。这意味着,如果您在

中定义了 class Foo::Bar::BazBoo class/module
  • Foo::Boo

Foo::Bar::Baz 中引用 Boo 实际上将以 Foo::Boo module/class 结束,而如果您使用 ::Boo 它将匹配 Boo 因为名称的解析将从主命名空间开始。