我找到一个成功地覆盖Time.strftime的源代码:
- class Time
- alias :old_strftime :strftime
- def strftime
- #do something
- old_strftime
- end
- end
麻烦的是,strftime是一个实例方法.我需要重写Time.now – 一个类的方法 – 这样就可以让任何调用者获取我的新方法,而新的方法仍然调用原来的.now方法.我看过alias_method,没有成功.
解决方法
这有时很难让你的头,但是你需要打开与特定类对象相关联的单例的“特征类”.其语法是class<<自己做...结束
- class Time
- alias :old_strftime :strftime
- def strftime
- puts "got here"
- old_strftime
- end
- end
- class Time
- class << self
- alias :old_now :now
- def now
- puts "got here too"
- old_now
- end
- end
- end
- t = Time.now
- puts t.strftime