views:

153

answers:

1

I have a Rails named_scope which is using a condition to pull specific days of the week from the table like so:

:conditions => [ 'EXTRACT(DOW FROM bookdate) IN (?)', (1..6).to_a ]

The 1..6 date range will be a variable depending on the dates the user wants,

Which produces this SQL

(EXTRACT(DOW FROM bookdate) IN (1,2,3,4,5,6)

My problem is that the days of the week are not a simple range... ie 1..6 works fine (Mon...Sat), but say 6..2 will not work correctly (Sat-Tues)... either as a ruby range or as it would need to be 6,7,1,2 and not 6,5,4,3,2 (assuming 6..2 worked in ruby, which it doesn't).

How can I create a custom range for days of the week that would accommodate a date range like this?

Any ideas?

Thanks,

+6  A: 

If you want a function to generate the range of values for inclusion in :conditions that will work for ranges like Sat-Tues as well as Mon-Sat how about:

def day_range(from, to)
  if from <= to
    (from..to).to_a
  else
    (from..7).to_a + (1..to).to_a
  end
end

e.g.

irb(main):032:0> day_range(1, 6)
=> [1, 2, 3, 4, 5, 6]
irb(main):033:0> day_range(6, 2)
=> [6, 7, 1, 2]

Then it is just a case of mapping the day names to the day numbers if required.

mikej