views:

121

answers:

3

What do you think the best way to generate a random DateTime in rails is? I am currently using the random_data gem to produce a random date, but it defaults all times at 12:00 AM. Here is an idea of what I'm trying to do (it's for a seeds.rb file). Also, maybe a random price within a certain range? I'm thinking I would need some sort of string manipulation but I'm new to rails and ruby so I'm still trying to wrap my head around all of it:


 Foo.create(:name => Faker::Lorem.words, :description => Faker::Lorem.sentence, :price => 6.54, :start_date => Random.date, :location_id => 1 + rand(1),:user_id => rand(20) + 1 )
A: 

I haven't tried this myself but you could create a random integer between two dates using the number of seconds since epoch. For example, to get a random date for the last week.

end = Time.now
start = (end - 1.week).to_i
random_date = Time.at(rand(end.to_i - start)) + start

Of course you end up with a Time object instead of a DateTime but I'm sure you can covert from here.

Randy Simon
A: 

Here are set of methods for generating a random integer, amount, time/datetime within a range.

def rand_int(from, to)
  rand_in_range(from, to).to_i
end

def rand_price(from, to)
  rand_in_range(from, to).round(2)
end

def rand_time(from, to)
  Time.at(rand_in_range(from.to_f, to.to_f))
end

def rand_in_range(from, to)
  rand * (to - from) + from
end

Now you can make the following calls.

rand_int(60, 75)
# => 61

rand_price(10, 100)
# => 43.84

rand_time(2.days.ago, Time.now)
# => Mon Mar 08 21:11:56 -0800 2010
KandadaBoggu
Awesome! thank you everyone!
Jack
+2  A: 

I prefer use (1..500).to_a.rand.days.ago

shingara
This code will throw syntax error (Range class doen't have the rand method)
KandadaBoggu
Yes you right. I change it. need call .to_a after range
shingara