Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change the value of Date.today within a running ruby process

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

like image 824
Joelio Avatar asked Oct 26 '10 17:10

Joelio


People also ask

How do I change the date format in Ruby?

Two steps: You need to convert your string into Date object. For that, use Date#strptime . You can use Date#strftime to convert the Date object into preferred format.

What is timestamp in Ruby?

Saying that »a true timestamp is the number of seconds since the Unix epoch« is a little missing the point, as that is one way of representing a point in time, but it also needs additional information to even know that you're dealing with a time and not a number.


1 Answers

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

like image 88
Ariejan Avatar answered Oct 27 '22 20:10

Ariejan