我找到了一个成功覆盖的来源Time.strftime
像这样:
class Time
alias :old_strftime :strftime
def strftime
#do something
old_strftime
end
end
问题是,strftime
是一个实例方法。我需要覆盖Time.now
- 类方法 - 任何调用者都可以获得我的新方法,而新方法仍然调用原始方法.now
方法。我看过alias_method
但没有取得成功。
有时这有点难以理解,但您需要打开“eigenclass”,它是与特定类对象关联的单例。其语法是 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)