2012-08-08 60 views
2

我有这样一个类:如何动态扩展/修改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 

,并处理NewClass类中String1参数。附加参数的处理器对于所有方法都是相同的。

回答

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。

+0

谢谢,这个作品完美! – 2012-08-08 16:00:43

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 
+0

是的,但有没有可能做到这一点,而不需要在“B”类中定义method_one方法? – 2012-08-08 15:42:18

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添加singleton方法如在上述的答案。