views:

37

answers:

3

Hi, I know this is a bad idea, but I have lots of legacy code and I want to run through some historical batch jobs. I dont want to change the systems date because other stuff runs on the same system. Is there any way that I can change the value that Date.today will return for the life of a given process only. The idea here is to rewind and run some older batch scripts that were used to work off of Date.today.

thanks Joel

A: 

you can redefine the 'today' class-method of the Date class

class Date
  def Date.today
    return Date.new(2000,1,1)
  end
end

this would fix Date.today to the 2000-01-01.

Nikolaus Gradwohl
ok cool, where do I put this code. I have a rails app, my batch file runs as a rake task. How do I make sure that only the rake task includes this code. Do I just put it in the rake task itself?
Joelio
including it in the rake task should work fine
Nikolaus Gradwohl
+4  A: 

You can either monkey-patch Ruby like Nikolaus showed you, or can use the TimeCop gem. It was designed to make writing tests easier, but you can use it in your normal code as well.

# Set the time where you want to go.
t = Time.local(2008, 9, 1, 10, 5, 0)

Timecop.freeze(t) do
   # Back to the future!
end
# And you're back!

# You can also travel (e.g. time continues to go by)
Timecop.travel(t)

It's a great, but simple piece of code. Give it a try, it'll save you some headaches when monkeypatching Date and Time yourself.

Link: https://rubygems.org/gems/timecop

Ariejan
+1 for TimeCop!
Jonathan
oh cool, I like this even better!
Joelio
A: 

If redefining Date.today seems too hacky, you can try delorean

From the github page:

require 'delorean'

# Date.today => Wed Feb 24
Delorean.time_travel_to "1 month ago" # Date.today => Sun Jan 24
Delorean.back_to_the_present          # Date.today => Wed Feb 24
Chubas