Skip to content

Instantly share code, notes, and snippets.

@adambeynon
Created October 2, 2014 21:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adambeynon/dd86f787f53e0a878f40 to your computer and use it in GitHub Desktop.
Save adambeynon/dd86f787f53e0a878f40 to your computer and use it in GitHub Desktop.
class AvailabilityChecker
def initialize(reservation)
@reservation = reservation
end
def available?
if @reservation.new_record?
new_record_available?
elsif @reservation.unit_id_changed?
update_unit_available?
elsif @reservation.arrive_changed? or @reservation.depart_changed?
update_record_available?
else
true
end
end
def new_record_available?
dates_available?(@reservation.arrive...@reservation.depart, @reservation.unit_id)
end
def update_unit_available?
dates_available?(@reservation.arrive...@reservation.depart, @reservation.unit_id)
end
def update_record_available?
new_dates = @reservation.arrive...@reservation.depart
old_dates = @reservation.arrive_was...@reservation.depart_was
check_range = new_dates.to_a - old_dates.to_a
dates_available?(check_range, @reservation.unit_id)
end
def dates_available?(date_range, unit_id)
capacity = Unit.find(unit_id).capacity
date_range.to_a.all? do |date|
pitch_count(date, unit_id) < capacity
end
end
def pitch_count(date, unit_id)
Pitch.find_or_create_by(date: date, unit_id: unit_id).count
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment