Best way to create random DateTime in Rails

前端 未结 12 1929
粉色の甜心
粉色の甜心 2020-12-22 23:49

What is the best way to generate a random DateTime in Ruby/Rails? Trying to create a nice seeds.rb file. Going to use it like so:

 Foo.create(name: Faker::Lo         


        
12条回答
  •  囚心锁ツ
    2020-12-23 00:30

    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.now)
      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)
    # => Mon Mar 08 21:11:56 -0800 2010
    

提交回复
热议问题