【问题标题】:Clone and patch class in ruby红宝石中的克隆和补丁类
【发布时间】:2022-11-21 18:51:12
【问题描述】:

我需要创建类的路径副本,其中对一个模块方法的调用被替换为另一个模块方法调用:

module Foo
    def self.check
        "foo"
    end
end

module Bar
    def self.check
        "bar"
    end
end

class Bark
    def call
        puts Foo.check
    end
end

Bark.new.call => "foo"

Meouw = Bark.dup

...

???

Meouw.new.call => "bar"

任何想法我将如何实现?

【问题讨论】:

    标签: ruby


    【解决方案1】:

    奇怪的问题需要奇怪的解决方案。您可以定义 Meouw::Foo 并使其引用 Bar

    Meouw = Bark.dup
    Meouw::Foo = Bar
    

    这样,Meouw内的Foo将解析为Meouw::Foo而不是全局的::Foo

    Meouw.new.call
    # prints "bar"
    

    【讨论】:

      【解决方案2】:

      不是问题的答案,但我认为你正在尝试解决 XY 问题,这不是解决问题的方法。

      您需要做的是注入依赖项而不是对其进行硬编码。

      module Foo
        def self.check
          "foo"
        end
      end
      
      module Bar
        def self.check
          "bar"
        end
      end
      
      class Bark
        def initialize(checker)
          @checker = checker
        end
      
        def call
          puts @checker.check
        end
      end
      

      然后用你需要的模块实例化 Bark 类以获得具有所需行为的对象:

      Bark.new(Foo).call #=> "foo"
      Bark.new(Bar).call #=> "bar"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-11-23
        • 2019-03-18
        • 2010-11-17
        • 1970-01-01
        • 1970-01-01
        • 2018-12-14
        • 2015-08-21
        • 1970-01-01
        相关资源
        最近更新 更多