如何覆盖有关注的内部类?

时间:2016-04-13 10:07:11

标签: ruby-on-rails ruby

我有一个包含另一个类的类。我希望有可能改变第二堂课。

以下是代码:

class BaseClass
  class InnerClass
    def sample;    puts 'sample'; end 
    def self.yolo; puts 'yolo';   end
  end
end

BaseClass::InnerClass.yolo       # yolo
BaseClass::InnerClass.new.sample # sample

module UglyButNeededPatch
  extend ActiveSupport::Concern

  included do
    class NewInnerClass
      def sample;    puts 'new sample'; end 
      def self.yolo; puts 'new yolo';   end
    end
    class InnerClass
      def sample;    super(); puts 'rewrite'; end 
      def self.yolo; super(); puts 'rewrite';   end
    end
  end
end

BaseClass.__send__(:include, UglyButNeededPatch)

这很好用

BaseClass::NewInnerClass.yolo       # new yolo
BaseClass::NewInnerClass.new.sample # new sample

这不起作用

BaseClass::InnerClass.yolo       # still display yolo
BaseClass::InnerClass.new.sample # still display sample

有没有办法让BaseClass::InnerClass.yolo显示yolorewriteBaseClass::InnerClass.new.sample显示samplerewrite

1 个答案:

答案 0 :(得分:2)

您可以像这样完全替换常量,例如:

module UglyButNeededPatch
  extend ActiveSupport::Concern

  included do |base|
    base::InnerClass = Class.new do
      def sample;    puts 'rewrite'; end 
      def self.yolo; puts 'rewrite';   end
    end
  end
end

如果你想手术修补内部类,我发现最简单的方法是使用另一个问题:

module UglyButNeededPatch
  extend ActiveSupport::Concern

  included do |base|
    base::InnerClass.include(InnerClassPatch)
  end

  module InnerClassPatch
    extend ActiveSupport::Concern

    def sample; puts 'rewrite'; end

    module ClassMethods
      def yolo; puts 'rewrite'; end
    end
  end
end