forked from bebanjo/delorean
/
delorean.rb
54 lines (42 loc) · 1.01 KB
/
delorean.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
require 'chronic'
module Delorean
extend self
def time_travel_to(time, options={})
mock_current_time(time, options)
return unless block_given?
begin
yield
ensure
restore_previous_time
end
end
def back_to_the_present
reset
end
alias :back_to_1985 :back_to_the_present
def jump(seconds)
mock_current_time Time.now + seconds
end
def now
Time.now_without_delorean - time_travel_offsets.inject(0){ |sum, val| sum + val }
end
private
def time_travel_offsets
@@time_travel_offsets ||= []
end
def reset
@@time_travel_offsets = []
end
def mock_current_time(time, options={})
time = Chronic.parse(time, options) if time.is_a?(String)
time = Time.local(time.year, time.month, time.day) if time.is_a?(Date) && !time.is_a?(DateTime)
time_travel_offsets.push Time.now - time
end
def restore_previous_time
time_travel_offsets.pop
end
end
class << Time
alias_method :now_without_delorean, :now
def now; Delorean.now; end
end