-
-
Save jacobat/3497259 to your computer and use it in GitHub Desktop.
Random time extention
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Date | |
# Samples a random time | |
# | |
# Parameters | |
# This takes up to three parameters, that is a range of `years`, `months` and | |
# `days`. Each defining the boundries of the sample date. | |
# | |
# Examples | |
# `Time.random({ years: 1..2 })` will produce a date between one and two | |
# ears into the future. | |
# | |
# `Time.random({ years: -5..5 })` will produce a date after five years ago, | |
# but before five ears from now. | |
# | |
# `Time.random({ years: 1..1 })` will produce a date within the next year | |
# | |
# `Time.random({ years: 1..1, months: 3..5 })` will produce a date within | |
# this year, and between march and may | |
# | |
# `Time.random({ years: 1..1, months: 3..5, days: 20..25 })` will produce a | |
# date between the 20th and 25th between march and may of this year. | |
# | |
def self.random(options = {}) | |
years = options[:years] || (-5..5) | |
months = options[:months] || (1..12) | |
year = years.to_a.collect{ |y| y >= 0 ? y.years.from_now.year : y.abs.years.ago.year }.sample | |
month = months.to_a.sample | |
days = options[:days] || (1..Date.civil(year, month, -1).day) | |
day = days.to_a.sample | |
Date.new(year, month, day) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment