Our Daily Method #14: Time#warp

Geplaatst door Remco van 't Veer vr, 22 feb 2008 08:00:00 GMT

Time travel can be very convenient but unfortunately it isn’t very easy. Reality won’t allow it but we can bend the Time class!


class Time
  def self.now_with_warping
    @warptime || now_without_warping
  end

  class << self
    alias_method :now_without_warping, :now
    alias_method :now, :now_with_warping
  end

  def warp
    self.class.instance_variable_set('@warptime', self)
    yield
  ensure
    self.class.instance_variable_set('@warptime', nil)
  end
end
Now we can travel back to “Unix Epoch”:

Time.at(0).warp do
  puts "The current time is: #{Time.now}" 
end
Or just before the end of time as we know it:

Time.at(2 ** 31 - 1).warp do
  Time.now + 1
end

What’s the use? It makes testing time dependent code very easy!

Geplaatst in , ,  | geen reacties

Reacties

(Laat url/e-mail achter »)

   Voorvertoning