如何在Ruby中动态扩展/修改继承类的所有方法?

时间:2012-08-08 15:08:50

标签: ruby

我有一个这样的课程:

class MainClass
  def self.method_one(String)
      puts "#{self.class} a"
  end
  def self.method_two(String)
      puts "#{self.class} a"
  end
end

我有一个继承MainClass

的类
class NewClass < MainClass
  #any_mathod should match any method that is called for NewClass call
  def self.any_method(a,b)
     puts "#{self.class} b"
     super(a)
  end
end

有什么方法可以在MainClass运行NewClass时从NewClass扩展所有方法,而无需在NewClass.method_one(String1, String2) 中重新定义它们以接受两个参数而不是一个,例如:

#=> NewClass String2
#=> MainClass String1

它会产生:

String1

并处理NewClass类中的{{1}}参数。所有方法的附加参数的处理器都是相同的。

3 个答案:

答案 0 :(得分:1)

也许你想要super方法

class A
  def self.method_one(a)
    puts "a is #{a}"
  end
end

class B < A
  (superclass.methods - superclass.superclass.methods).each do |m|
    define_singleton_method(m) do |a, b|
      puts "b is #{b}"
      super(a)
    end
  end
end

B.method_one(5, 10)

# => b is 10
# => a is 5

答案 1 :(得分:1)

试试这个:

class MainClass
    def self.method_one(string)
        puts string
    end
    def self.method_two(string)
        puts string
    end
end


class NewClass < MainClass
    #Iterate through all methods specific to MainClass and redefine
    (self.superclass.public_methods - Object.public_methods).each do |method|
        define_singleton_method method do |string1, string2|
            #Common processing for String1
            puts string1 

            #Call the MainClass method to process String2
            super(string2)
        end
    end
end

NewClass将遍历MainClass中专门定义的所有方法。然后它将为NewClass定义一个处理String1的类方法,然后调用MainClass方法来处理String2。

答案 2 :(得分:0)

另一种方法是放弃继承并改为使用模块:

module TestModule
  def awesome1
  end
  def awesome2
  end
end

class TestClass
  def self.include mod
    puts (mod.instance_methods - Module.methods).sort
    super
  end
  include TestModule
end

在重写的#include中添加单例方法,如上面的答案所示。