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?
Overlap = min(A2, B2) - max(A1, B1) + 1. In other words, the overlap of two integer intervals is a difference between the minimum value of the two upper boundaries and the maximum value of the two lower boundaries, plus 1.
Basically, a period can be represented by a line fragment on time axis which has two boundaries; starttime and endtime. To claim two time periods to be overlapping, they must have common datetime values which is between lower and upper limits of both periods.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With