Friday 7 March 2008

Date ranges from a list of dates

You need date ranges before you can use acts_as_line. Often you will just have a list of booked dates.

I've pluginized my date range method, which takes a collection of dates and finds the ranges: date_ranger

DateRanger
==========

Identify start/end dates in a set.

Example
=======

require 'date_ranger'
require 'date'

dates = %w(2008-04-26 2008-04-27 2008-04-28 2008-04-29 2008-04-30 2008-05-01 2008-05-02 2008-05-24 2008-05-25 2008-05-26 2008-05-27 2008-05-28 2008-05-29 2008-05-30 2008-07-12 2008-07-13 2008-07-14 2008-07-15 2008-07-16 2008-07-17 2008-07-18 2008-07-26 2008-07-27 2008-07-28 2008-07-29 2008-07-30 2008-07-31 2008-08-01 2008-08-09 2008-08-10 2008-08-11 2008-08-12 2008-08-13 2008-08-14 2008-08-15 2008-08-16 2008-08-17 2008-04-21 2008-04-21 2008-08-18 2008-08-19 2008-04-23 2008-08-20 2008-04-22 2008-08-21 2008-08-22 2008-12-27 2008-12-28 2008-12-29 2008-12-30 2008-12-31 2008-03-29 2008-03-30 2008-03-31 2008-04-01 2008-04-02 2008-04-03 2008-04-04 2008-04-05 2008-04-06 2008-04-07 2008-04-08 2008-04-09 2008-04-10 2008-04-11 2008-04-12 2008-04-13 2008-04-14 2008-04-15 2008-04-16 2008-04-20 2008-04-17 2008-04-18 2008-05-24 2008-05-25 2008-05-26 2008-05-27 2008-05-28 2008-05-29 2008-05-30 2008-05-31 2008-06-01 2008-06-02 2008-06-03 2008-06-04 2008-06-05 2008-06-06 2008-07-05 2008-07-06 2008-07-07 2008-07-08 2008-07-09 2008-07-10 2008-07-11 2008-07-12 2008-07-13 2008-07-14 2008-07-15 2008-07-16 2008-07-17 2008-07-18 2008-07-19)

bookings = DateRanger.new(dates)
p bookings.ranges

>> [{"end"=>"2008-04-18", "start"=>"2008-03-29"}, {"end"=>"2008-04-23", "start"=>"2008-04-20"}, {"end"=>"2008-05-02", "start"=>"2008-04-26"}, {"end"=>"2008-06-06", "start"=>"2008-05-24"}, {"end"=>"2008-07-19", "start"=>"2008-07-05"}, {"end"=>"2008-08-01", "start"=>"2008-07-26"}, {"end"=>"2008-08-22", "start"=>"2008-08-09"}, {"end"=>"2008-12-31", "start"=>"2008-12-27"}]

csv = bookings.to_csv('|')
bookings.csv.each {|row|
p row
}

gives:

"2008-03-29|2008-04-18"
"2008-04-20|2008-04-23"
"2008-04-26|2008-05-02"
"2008-05-24|2008-06-06"
"2008-07-05|2008-07-19"
"2008-07-26|2008-08-01"
"2008-08-09|2008-08-22"
"2008-12-27|2008-12-31"


UPDATE:

gem install dateranger

api has changed slightly in the gem release:

DateRanger::Range.new(dates_array)

Plugin is best at this stage, easier to hack.

No comments: