【问题标题】:How does '::' at the beginning of the class affect scope (ruby/rails)?类开头的“::”如何影响范围(ruby/rails)?
【发布时间】:2015-08-24 13:35:28
【问题描述】:

我正在一个大型 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 类名与 app/services 类名相同。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 class inheritance


    【解决方案1】:

    前导 :: 强制 Ruby 解释器开始从顶级命名空间解析类名。这意味着,如果你有一个类 Foo::Bar::BazBoo 类/模块在两者中定义

    • Foo::Boo

    Foo::Bar::Baz 中引用Boo 实际上最终会到达Foo::Boo 模块/类,而如果您使用::Boo,它将匹配Boo,因为名称的解析将从主命名空间开始.

    【讨论】:

    • 谢谢 - 这正是我想要的。
    猜你喜欢
    • 2022-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-26
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多