How to get a random datetime in a rake populate task?

378 Views Asked by At
  User.all.each do |user|
    7.times do
      user.schedules.create!(:user_id => user.id, :start_time => Time.now, :length => 25)
    end
  end

How can I replace the Time.now with a Time.random method? I found this to help with getting random datetimes, but how can I use this method in a Rake task?

1

There are 1 best solutions below

0
On BEST ANSWER

The article you cite reopens the Time class and add the random method. So, while I wouldn't advocate doing it you can just add the

class Time       
   def self.random(params={})
      ...
   end

end

directly to your rake file. Another approach would be to add this code to a file in your lib directory - 'monkey_patch_time.rb', and then add

require 'monkey_patch_time'

to the top of your rake file. I like this approach better, as it lets you use this method in other places. Additionally, I like to collect all my monkey patches in a central location.