Reputation: 626
I need to implement booking functionality and ensure that bookings don't overlap in a Rails app.
The cover?
and between?
methods aren't quite what I need. I have to ensure uniqueness of a time range when compared to other potential ranges on the same model, and do it efficiently.
I THINK it can be done using overlaps?
. The problem is that this returns TRUE for something like this:
(1..5).overlaps?(5..9)
=> true
If I compared a booking that ended right when another started (3:30 - 4:00
versus 4:00 - 4:30
), it would say they do overlap, but they technically don't. That would be a problem right?
ValidatesOverlap seems to handle the issue, including edge overlap.
Any suggestions?
Upvotes: 7
Views: 6776
Reputation: 695
For your scenario, why do we have to include end time? After all, booking is finished at that time and slot is available from that time onwards. So below should make sense.
(1...5).overlaps?(5...9)
Upvotes: 6
Reputation: 9344
def overlap?(x,y)
(x.first - y.end) * (y.first - x.end) > 0
end
will work. The problem is that Interval
uses >=
, as you can see in "Test if two date ranges overlap in Ruby or Rails".
Upvotes: 11