Created
November 26, 2013 14:56
-
-
Save darrencauthon/7659725 to your computer and use it in GitHub Desktop.
Ways of dealing with time in Ruby. These are meant to be alternatives to the many options of constructor/parameter injection of mocked time objects in static languages or ambitious architects.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'time' | |
require 'timecop' | |
Timecop.freeze Time.parse('1/1/2011') | |
# All Ruby date functions have been overridden, | |
# so I can access them in my code directly without | |
# constructor or parameter injection. | |
Time.now # 2011-01-01 00:00:00 -0600 | |
Date.today # <Date: 2011-01-01 ((2455563j,0s,0n),+0s,2299161j)> | |
# let's return back to the correct date | |
Timecop.return | |
Date.today # <Date: 2013-11-26 ((2456623j,0s,0n),+0s,2299161j)> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'mocha/setup' | |
require 'time' | |
# I can mock Time.now directly, returning a specific date... | |
Time.stubs(:now).returns Time.parse('1/1/2011') | |
Time.now #2011-01-01 00:00:00 -0600 | |
# ... but doing so binds me to one particular way of getting the mocked date/time. | |
Date.today #<Date: 2013-11-26 ((2456623j,0s,0n),+0s,2299161j)> | |
# If I'm merely passing the time along to another method or class, | |
# I can even use an object reference to easily verify that the | |
# right value was used. | |
my_time = Object.new #<Object:0x007fdf7489ed78> | |
Time.stubs(:now).returns my_time | |
Time.now #<Object:0x007fdf7489ed78> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# I can even override Time itself, changing its behavior | |
# for my app. | |
def Time.now | |
1 | |
end | |
Time.now # 1 | |
# Obviously, I don't do this, but this just shows how | |
# flexible Ruby can be. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment