开发者

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

  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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜