Created
June 26, 2012 08:49
-
-
Save sivabudh/2994481 to your computer and use it in GitHub Desktop.
Implementation of the implementation we talked about yesterday.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'chronic' | |
class Scheduler | |
def self.process(params) | |
raise 'start_date must be supplied' if params[:start_date].nil? | |
raise 'end_date must be supplied' if params[:end_date].nil? | |
raise 'occurs_on must be supplied' if params[:occurs_on].nil? | |
start_date = DateTime.parse params[:start_date] | |
end_date = DateTime.parse params[:end_date] | |
selected_days = params[:occurs_on].map { |day, _| day.to_i } | |
raise 'End date cannot earlier than start date' if end_date < start_date | |
num_days = (end_date - start_date).to_i | |
# Collect all the dates between start_date and end_date | |
dates = [start_date] | |
num_days.times do | |
tomorrow = dates.last.advance days: 1 | |
dates.push tomorrow | |
end | |
# Select only dates whose day is what the user selected | |
dates_to_be_scheduled = [] | |
selected_days.each do |day| | |
dates_to_be_scheduled.push dates.select { |date| date.wday == day } | |
end | |
dates_to_be_scheduled.flatten.sort | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment