How to change Date.today value during a running ruby ​​process

I know this is a bad idea, but I have a lot of old code, and I want to run some historical batch jobs. I do not want to change the date of the system, because other things work on the same system. Is there a way to change the value that Date.today will return for the life of only a specific process. The idea here is to rewind and run some old scripts that were used for Date.today to work.

thanks Joel

+6
date ruby ruby-on-rails
source share
3 answers

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

# 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 (eg time continues to go by) Timecop.travel(t) 

This is a great but simple piece of code. Try it, it will save you some headaches when you both have a date and time.

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

+6
source share

you can override the "today's" method class of the Date class

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

this will set Date.today to 2000-01-01.

0
source share

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

On 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 
0
source share

All Articles