如果你想重构某个类中的某个方法的名字,可是又不想影响已经调用该方法的其他代码,该如何处理呢?可以使用“类宏”技术,请看下面的代码:
class MyClass def old_method(name) puts "hello " + name end def new_method(name) puts "hello " + name end def self.deprecate(old_method, new_method) define_method(old_method) do |*args, &block| warn "Warning: #{old_method}() is deprecated. Use #{new_method}()." send(new_method, *args, &block) end end deprecate :old_method, :new_method end obj = MyClass.new obj.old_method("koska")
输出结果:
Warning: old_method() is deprecated. Use new_method(). hello koska
deprecate :old_method, :new_method 这样的代码会让你觉得deprecate很像一个关键字,其实它也只是一个普通的方法而已,只是可以用在类定义中而已,这样的方法被称为“类宏”。
在这个方法中,定义了一个叫old_method的方法,并把对这个方法的调用参数以及块都转发给了new_method,并在转发前在控制台打印出警告信息,此方法已经过期,建议大家使用新的方法。