I am working on an hourly hotel booking application. There is a peak_seasons
table which stores start_date
and end_date
. Peak_Seasons are pre-defined dates for current year in my application. Whenever a customer makes a booking for the selected hours then I have to check if any of those hours belongs to peak season, so that I can apply a different rate for those hours.
This operation is so frequent that I want to optimise it. Need ideas. My current pseudo code is this:
def calculate_price(customer_start_time, customer_end_time)
price = 0
(customer_start_time.to_i...customer_end_time.to_i).step(1.hour) do |hour|
//now check if this hour belongs to peak season over here
if peak_seasons?(hour)
price += price + peak_season_price
else
price += price + standard_price
end
return price
end
//peak_seasons? somewhere
def peak_seasons?(hour)
PeakSeason.where("start_date <= ? and end_date >= ?", hour.to_date, hour.to_date).any?
end
I guess this is not efficient code when hundreads of customers are checking the price for selected hours, then it will fetch data from DB for every hour selected. How to optimize it?