如何一个 - 没有继承 - 重写一个类方法,并从新的方法中调用原始? [英] How does one - without inheritance - override a class method and call the original from within the new method?
问题描述
我找到一个成功替代 Time.strftime
的来源,如下所示:
I found one source which successfully overrode Time.strftime
like this:
class Time
alias :old_strftime :strftime
def strftime
#do something
old_strftime
end
end
麻烦的是, strftime
是一个实例方法。我需要重写 Time.now
- 一个类方法 - 在任何调用者获取我的新方法,而新方法仍然调用原来的 .now
方法。我看过 alias_method
,并且没有成功。
The trouble is, strftime
is an instance method. I need to override Time.now
- a class method - in such away that any caller gets my new method, while the new method still calls the original .now
method. I've looked at alias_method
and have met with no success.
推荐答案
这有时很难得到你的头,但是你需要打开eigenclass这是与特定类对象相关联的单例。该语法是类<<自我...结束。
This is kinda hard to get your head around sometimes, but you need to open the "eigenclass" which is the singleton associated with a specific class object. the syntax for this is class << self do...end.
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
这篇关于如何一个 - 没有继承 - 重写一个类方法,并从新的方法中调用原始?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!