Skip to content

Instantly share code, notes, and snippets.

@renanra
Created April 30, 2012 18:59
Show Gist options
  • Save renanra/2561332 to your computer and use it in GitHub Desktop.
Save renanra/2561332 to your computer and use it in GitHub Desktop.
random_date ruby/rails
# 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