Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date range in ruby/rails

I want to get date range between from and till in Rails seed.

When I try to generate date range ((Date.today - 10)..Date.today) exception occurred.

Exception message: bad value for range

But in the Rails Console everything all right.

I think ActiveSupport are reasonable for that (my debugger told me that).

Ralls 3.1.3

What's going on?

like image 211
Paul Brit Avatar asked Dec 12 '22 03:12

Paul Brit


2 Answers

You can understand what's going on by splitting the two edges and check their class like so:

Date.today.class #  => Date 
(Date.today - 10).class # => Date 
((Date.today - 10)..Date.today).each {|d| puts d.class} # => 10 Date works for me

The error you're experiencing is something like this:

('a'..10) # => ArgumentError: bad value for range

Can you post the classes of your 2 edges of the range?

(Date.today - 10).class => ?
Date.today.class       => ?

Have you overwritten any class in your rails environment? Does it work in irb?

PS: As you're in rails you can use 10.days.ago but you'll need to use to_date as it's a ActiveSupport::TimeWithZone

like image 100
ecoologic Avatar answered Dec 29 '22 21:12

ecoologic


begin
  ((Date.today - 10)..Date.today).each { |date| puts date }
rescue
  $! # => #<NameError: uninitialized constant Date>
end

require 'date'
((Date.today - 10)..Date.today).each { |date| puts date }
# >> 2012-04-06
# >> 2012-04-07
# >> 2012-04-08
# >> 2012-04-09
# >> 2012-04-10
# >> 2012-04-11
# >> 2012-04-12
# >> 2012-04-13
# >> 2012-04-14
# >> 2012-04-15
# >> 2012-04-16
like image 38
Joshua Cheek Avatar answered Dec 29 '22 21:12

Joshua Cheek