1

I've got this rudimentary example

module TheirModule
  class Klass

    def self.do_something
      KlassModule.klass_module_method()
    end

    module KlassModule

      # Lots of other functionality

      def self.klass_module_method
        puts "Hello from TheirModule"
      end

      # Lots of other functionality

    end
  end
end

module MyModule
  class Klass < TheirModule::Klass

    module KlassModule
      extend TheirModule::Klass::KlassModule

      def self.klass_module_method
        puts "Hello from MyModule"
      end

    end
  end
end

Then calling this gives me unexpected results.

MyModule::Klass.do_something  # Hello from TheirModule

My expectation is that MyModule::Klass's KlassModule will redefine the klass_module_method originally defined in TheirModule::Klass's KlassModule like this...

MyModule::Klass.do_something  # Hello from MyModule

this clearly isn't the case and I'm wondering...

  • Why this doesn't work?
  • What would be a ruby way to accomplish this?

EDIT: The one caveat is that I cannot edit the source of TheirModule

4

2 回答 2

1

这将在不修改原始代码的情况下工作TheirModule

有两个 KlassModule

  • TheirModule::Klass::KlassModule
  • MyModule::Klass::KlassModule

TheirModule::Klassname内KlassModule明确解析为TheirModule::Klass::KlassModule. 您定义的另一个模块与这个模块完全分开。它不能重新定义任何东西。

您需要打开并更改原始模块TheirModule::Klass::KlassModule. 例如,像这样。

module MyModule
  class Klass < TheirModule::Klass

    module ::TheirModule::Klass::KlassModule
      def self.klass_module_method
        puts "Hello from MyModule"
      end

    end
  end
end

MyModule::Klass.do_something
# >> Hello from MyModule

虽然我会说这看起来不是一个非常红宝石的方式。也许可以重新组织类和模块以更清洁的方式实现这一点。

于 2013-10-10T16:23:46.117 回答
0

非常简单的修复。试试这个self.do_something

def self.do_something
  self::KlassModule.klass_module_method()
end

这会强制方法在当前类的上下文中查找KlassModule

于 2013-10-10T16:26:08.110 回答