Created
April 30, 2012 18:59
-
-
Save renanra/2561332 to your computer and use it in GitHub Desktop.
random_date ruby/rails
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
# USAGE: | |
# random_date() # => random date within 20 days past | |
# random_date(30) # => random date within 30 days past | |
# random_date(:unity => :second) => random date within 20 seconds past | |
# random_date(:future => true) => random date within 20 days future and past | |
# random_date(:past => false) => random date within 20 days future | |
# random_date(4.years, :unity => :second, :past => false) => random date withim 4 years future. Random year til second | |
# random_date(4, :unity => :years, :past => false) => random date withim 4 years future. Actual date with random year only | |
def random_date(*arguments) | |
options = { | |
:future => false, | |
:past => true, | |
:unity => :day | |
} | |
options.merge!(arguments.last) if (arguments.last.kind_of? Hash) | |
range = arguments.first if arguments.first.kind_of? Fixnum | |
range ||= 20 | |
Time.now | |
rand(range).days | |
operator = | |
if options[:future] && options[:past] | |
rand(2) == 1 ? :+ : :- | |
elsif options[:future] | |
:+ | |
else | |
:- | |
end | |
Time.now.send(operator, rand(range).send(options[:unity])) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment