2008-11-13 46 views

回答

11

這是有點難以有時身邊讓你的頭,但你需要打開「eigenclass」,這是一類特殊對象關聯的單。這個語法是類< < 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 
2

類方法只是方法。我強烈推薦針對這一點,但你有兩個等同的選擇:

class Time 
    class << self 
    alias_method :old_time_now, :now 

    def now 
     my_now = old_time_now 
     # new code 
     my_now 
    end 
    end 
end 

class << Time 
    alias_method :old_time_now, :now 

    def now 
    my_now = old_time_now 
    # new code 
    my_now 
    end 
end 
1

如果你需要重寫它用於測試目的(的原因,我通常要重寫Time.now),紅寶石嘲諷/斯塔賓框架會爲你輕鬆做到這一點。例如,使用RSpec(使用flexmock):

Time.stub!(:now).and_return(Time.mktime(1970,1,1)) 

順便說一句,我強烈建議避免了需要通過給你的類的覆寫投放時鐘存根出Time.now:

class Foo 
    def initialize(clock=Time) 
    @clock = clock 
    end 

    def do_something 
    time = @clock.now 
    # ... 
    end 
end 
0

我我一直在想弄清楚如何用模塊重載實例方法。

module Mo 
    def self.included(base) 
    base.instance_eval do 
     alias :old_time_now :now 
     def now 
     my_now = old_time_now 
     puts 'overrided now' 
     # new code 
     my_now 
     end 
    end 
    end 
end 
Time.send(:include, Mo) unless Time.include?(Mo) 

> Time.now 
overrided now 
=> Mon Aug 02 23:12:31 -0500 2010