通过在模块中混合来覆盖类的实例方法 [英] Overriding instance methods of a class by mixing in a module

查看:274
本文介绍了通过在模块中混合来覆盖类的实例方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个类A和一个模块B,将B的实例方法混合在一起,以使其覆盖A的相应实例方法.

Given a class A and a module B, mixin the instance methods of B so that it overrides the correspnding instance methods of A.

module B
  def method1
    "B\#method1"
  end

  def method2
    "B\#method2"
  end
end

class A
  def method1
    "A\#method1"
  end

  def method2
    "A\#method2"
  end

  # include B    does not override instance methods!
  #              (module gets mixed into the superclass)
end

puts A.new.method1   # want it to print out "B#method1"
puts A.new.method2   # want it to print out "B#method2"

推荐答案

您可以在包含B之前从A中删除B的每个方法.

You could remove each of B's methods from A before including B.

class A
  def method1
    "A\#method1"
  end

  def method2
    "A\#method2"
  end

  B.instance_methods(false).each { |method|
    remove_method(method) if instance_methods(false).include?(method)
  }
  include B
end

或从B内部:

module B
  def method1
    "B\#method1"
  end

  def method2
    "B\#method2"
  end

  def self.append_features(mod)
    instance_methods(false).each { |method|
      mod.send(:remove_method, method) if mod.instance_methods(false).include?(method)
    }
    super
  end
end

这篇关于通过在模块中混合来覆盖类的实例方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆