This post originated from an RSS feed registered with Ruby Buzz
by Obie Fernandez.
Original Post: Even Better Random Times for Rails
Feed Title: Obie On Rails (Has It Been 9 Years Already?)
Feed URL: http://jroller.com/obie/feed/entries/rss
Feed Description: Obie Fernandez talks about life as a technologist, mostly as ramblings about software development and consulting. Nowadays it's pretty much all about Ruby and Ruby on Rails.
First of all, I switched to using a hash parameter to the function, to simulate named parameters just like Rails does. The year_range parameter is still supported, dictating how far back to go for our date, in years. I also added a series parameter, which tells the function to generate a sequence of random dates instead of only one.
class Time
def self.random(params={})
years_back = params[:year_range] || 5
year = (rand * (years_back)).ceil + (Time.now.year - years_back)
month = (rand * 12).ceil
day = (rand * 31).ceil
series = [date = Time.local(year, month, day)]
if params[:series]
params[:series].each do |some_time_after|
series << series.last + (rand * some_time_after).ceil
end
return series
end
date
end
end
Why the added complexity and multiple return types? Cause it's a lot more useful that way.
Loading development environment.
>> # a random date
?> Time.random
=> Tue Aug 05 00:00:00 EDT 2003
>>
?> # birthdays, anyone?
?> 5.times { p Time.random(:year_range=>80) }
Wed Feb 06 00:00:00 EDT 1974
Tue Dec 22 00:00:00 EST 1992
Fri Apr 14 00:00:00 EWT 1944
Thu Jul 01 00:00:00 EDT 1993
Wed Oct 02 00:00:00 EDT 2002
=> 5
>>
?> # series of dates are useful for account-related info
?> Time.random :series => [20.days, 3.years]
=> [Sat Jan 22 00:00:00 EST 2005,
Sat Jan 29 12:58:45 EST 2005,
Fri Sep 08 09:34:58 EDT 2006]
>>
?> # or maybe to simulate events during an hour?
?> Time.random :series => [1.hour,1.hour,1.hour]
=> [Wed Apr 21 00:00:00 EDT 2004,
Wed Apr 21 00:45:59 EDT 2004,
Wed Apr 21 01:02:47 EDT 2004,
Wed Apr 21 01:31:00 EDT 2004]
Check this out: with the following snippet I accomplish exactly what I was after with regards to populating my database with some realistic sample data. BTW, I'm going to wrap up a polished version of this extension (along with some more sample data goodies that I thought up while I was writing this one) and publish them as a plugin later. Stay tuned for that.
The screenshot shows a portion of my IntelliJ screen, with the SimpleSyntax plugin (for Ruby support) and the SQL plugin (for adhoc queries and schema inspection)