【问题标题】:Allow unqualified access to Ruby constants in a different module允许对不同模块中的 Ruby 常量进行无限制访问
【发布时间】:2015-10-05 23:49:25
【问题描述】:

根据this answer,可以在顶层使用include 将常量放入global 命名空间,至少在IRB 中是这样。天真地,我以为我可以在模块内做同样的事情:

module Foo
  class Bar
    def frob(val)
      "frobbed #{val}"
    end
  end
end

module Baz
  include Foo
  class Qux
    def initialize(val)
      @val = val
      @bar = Bar.new
    end
    def twiddle
      @bar.frob(@val)
    end
  end
end

但是,尝试使用它会产生:

NameError: uninitialized constant Baz::Qux::Bar

然后我尝试覆盖 Baz::const_missing 以转发到 Foo,但它没有被调用。 Baz::Qux::const_missing 可以,但我想到那时解释器已经放弃查看 Baz。

如何将Foo 常量导入Baz 以便Baz 下的类不必限定它们?

(请注意,为了目录结构和模块名称之间的一致性,我不想在Foo 中声明Qux 等而不是Baz。)


ETA:如果我创建另一个类Baz::Corge,Baz::Qux 可以无条件引用它。很明显,存在某种“对等范围”的感觉。我知道有几种方法可以让Qux 访问Bar,但我正在寻找一种方法让Baz 中的所有 类访问Bar(和Foo) 中的所有其他课程,没有资格。

【问题讨论】:

  • 我会说 Ruby 出乎意料? 无法解析 Bar 常量,尽管它位于最近的外部范围中,因为它是一个 继承的 i> 常量,不是接收器的常量 - 模块 Baz。我找不到明确答案的来源,无法确定这是预期行为还是实现中的错误。在最新的 CRuby 2.2.3 和 2.0.0 版本中也存在同样的问题。
  • 是否意味着,继承的常量是否只能在与调用点相同的范围内直接访问,否则只能完全限定?不太清楚,也许有资深的 Ruby 专家能说清楚?

标签: ruby module namespaces method-missing


【解决方案1】:

好的.. 问题是常量(由于某种原因)没有在Quz class 中定义,而是在上层范围the module Baz scope 中定义。 如果我们能以某种方式将(当前单词?)Quz 中的常量调用委托给上层(Baz)范围 - 我们可以:

使用Module#const_missing

我将展示两次:一次用于您的私人案例,一次用于更一般的方法。

1) 解决私人案件:

module Foo
  class Bar
    def frob(val)
      "frobbed #{val}"
    end
  end
end

module Baz
  include Foo
  class Qux
    def self.const_missing(c)
      #const_get("#{self.to_s.split('::')[-2]}::#{c}")
      const_get("Baz::#{c}")
    end

    def initialize(val)
      @val = val
      @bar = Bar.new
    end
    def twiddle
      @bar.frob(@val)
    end
  end
end

puts Baz::Qux.new('My Value').twiddle

那么这里会发生什么?几乎相同的事情 - 只是在收到错误时 - 它有点被拯救并到达(或回退到)const_missing function 以接收新值 - 这适用于常量和类(显然它们是相同的类型)。

但这意味着我们必须将 self.const_missing(c) 方法添加到模块 Baz 中的每个类中 - 或者我们可以迭代模块 Baz 中的每个类并添加它(可能有更好的方法来做到这一点,但它有效)


2) 更自动化的方法:

module Foo
  class Bar
    def frob(val)
      "frobbed #{val}"
    end
  end
end

module Baz

  class Qux
    def initialize(val)
      @val = val
      @bar = Bar.new
    end

    def twiddle
      @bar.frob(@val)
    end
  end

  def self.add_const_missing_to_classes
    module_name = self.to_s

    #note 1
    classes_arr = constants.select{|x| const_get(x).instance_of? Class} #since constants get also constants we only take classes

    #iterate classes inside module Baz and for each adding the const_missing method
    classes_arr.each do |klass| #for example klass is Qux
      const_get(klass).define_singleton_method(:const_missing) do |c|
        const_get("#{module_name}::#{c}")
      end
    end
  end

  add_const_missing_to_classes

  #we moved the include Foo to the end so that (see note1) constants doesn't return Foo's classes as well
  include Foo
end

puts Baz::Qux.new('My Value').twiddle

在模块 Baz 的末尾,在定义了所有类之后。我们迭代它们(在add_const_missing_to_classes 方法中)。要选择它们,我们使用 Module#constants 方法返回一个模块常量数组 - 表示 CONSTANTS 和 CLASSES,因此我们使用 select 方法仅适用于类。

然后我们迭代找到的类并将const_missing类方法添加到类中。

请注意,我们将 include Foo 方法移到了末尾 - 因为我们希望 constants 方法不包含来自模块 Foo 的常量。

当然有更好的方法来做到这一点。但我相信OP的问题:

如何将 Foo 常量导入 Baz,这样 Baz 下的类就不必限定它们?

已回答

【讨论】:

  • 这只有在Baz 中的所有类都在add_const_missing_to_classes 被调用之前定义才有效,对吗?
  • 是的,这就是它在最后被调用的原因。但这是我在课程中添加const_missing 的方式——你可以随心所欲地进行
【解决方案2】:

这是我最终想出的。在最初声明 Baz 的同一个文件中:

module Foo
  def self.included(base)
    constants.each { |c| base.const_set(c, const_get("#{self}::#{c}")) }
  end
end

module Baz
  include Foo
  #... etc.
end

当Baz包含Foo时,它会为每个Foo::Whatever设置一个对应的常量Baz::Whatever,以Foo::Whatever为值。

如果您担心Foo 可能已经定义了self.included,您可以使用alias_method 进行调整:

module Foo
  alias_method :old_included, :included if self.method_defined? :included
  def self.included(base)
    old_included(base) if method_defined? :old_included
    constants.each { |c| base.const_set(c, const_get("#{self}::#{c}")) }
  end
end

这种方法有两个限制 --

  1. 我们关心的Foo 中的所有常量(包括类)必须在评估include Foo 时定义——以后添加到Foo 的扩展将不会被捕获。
  2. 此处定义Foo.included 的文件必须在Baz 中使用任何这些常量的任何文件之前需要——如果客户端只是使用require 'baz' 来拉入一个baz.rb 则足够简单,而baz.rb 又使用Dir.glob 或类似文件加载所有其他 Baz 文件,但重要的是不要直接要求这些文件。

Roko's answer 使用const_missing 解决了上述问题(1),但它仍然存在与(2)类似的问题,即必须确保在定义Baz 中的所有类之后调用add_const_missing_to_classes .可惜有no const_added hook。

我怀疑const_missing 方法在性能方面也会受到影响,因为每个常量引用都依赖于const_missing 和const_get。这可能会通过缓存结果的混合来缓解,即通过在const_missing 中调用const_set,但我没有探索过这一点,因为试图弄清楚define_singleton_method 内部的范围总是让我头疼。

【讨论】:

    【解决方案3】:

    从给出的错误中可以看出:NameError: uninitialized constant Baz::Qux::Bar

    它试图在Qux class 范围内找到Bar class - 但在那里找不到 - 为什么会这样?

    因为它不在此范围内 - 它在 Baz modlue 范围内,您使用了 include Foo

    所以你有两个选择: 1) 调用Bar class 时处理正确的范围, 所以改变这个:

    @bar = Bar.new
    

    进入这个:

    @bar = Baz::Bar.new
    

    像这样:

    module Baz
      include Foo
      class Qux
        def initialize(val)
          @val = val
          @bar = Baz::Bar.new
        end
        def twiddle
          @bar.frob(@val)
        end
      end
    end
    

    或者,

    2) 将include Foo 插入class Qux 本身:

    module Baz
      class Qux
        include Foo
        def initialize(val)
          @val = val
          @bar = Bar.new
        end
        def twiddle
          @bar.frob(@val)
        end
      end
    end
    

    --编辑--

    正如 joanbm 所说,这并不能解释这种行为。你可能想看看Scope of Constants in Ruby Modules。虽然那篇文章是关于常量(不是类)的,但原理是一样的。

    【讨论】:

    • 但这并不能解释 Module#include 的行为。尝试在module Baz 范围内以另一种方式定义一个常量,例如Bang = 123 或const_set :Bang, 123,或者定义一个类,来自Qux#initialize 的非限定访问将得到正确解决。
    • 是的,我知道有几种方法可以让Qux 访问Bar,但我正在为所有类寻找一种方法在Baz 中访问Bar(以及Foo 中的所有其他类),无需资格。
    【解决方案4】:

    由于 Foo 包含在 Baz 中,因此可以找到 Bar —— Qux 中没有。所以你可以改变

    @bar = Bar.new
    

    到

    @bar = Baz::Bar.new
    

    或将 include Foo 移动到 class Qux

    【讨论】:

    • 如问题中所述,我知道有几种方法可以让Qux 访问Bar。我正在寻找方法让Baz 中的所有 类访问Bar(以及Foo 中的所有其他类)没有 资格。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-20
    • 2017-12-28
    • 1970-01-01
    • 2013-06-07
    • 2020-12-26
    • 2015-05-25
    相关资源
    最近更新 更多