Created
September 14, 2022 15:12
-
-
Save jcreed/7dc7ce872de5107ea4d5b369a0ccd6b4 to your computer and use it in GitHub Desktop.
concept run_at
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
class ScheduleNextRunAt | |
MONTHS = { "30" => [1,3,4,5,6,7,8,9,10,11,12], "31" => [1,3,5,7,8,10,12] }.freeze | |
def initialize(date, schedule_option, advance_to_date=nil) | |
@date = date | |
@schedule_option = schedule_option | |
@advance_to_date = advance_to_date | |
end | |
def next_run_date | |
debugger | |
return @date unless @date.is_a?(DateTime) | |
if @advance_to_date.is_a?(DateTime) | |
@date = set_date_to_current_day | |
else | |
case @schedule_option | |
when 'daily' | |
calc_next_day | |
when 'weekly' | |
calc_next_week | |
when 'monthly' | |
calc_next_month | |
else | |
@date | |
end | |
end | |
end | |
private | |
def calc_next_day | |
@date.next_day | |
end | |
def calc_next_week | |
@date.next_occurring(@date.strftime("%A").downcase.to_sym) | |
end | |
def calc_next_month | |
month = @date.month | |
date = case @date.day | |
when 1..28 | |
@date.next_month | |
when 29 | |
if @date.leap? || @date.month > 1 | |
@date.next_month | |
else | |
@date + 2.months | |
end | |
when 30..31 | |
if month == 12 | |
@date.next_month | |
else | |
@date + (calc_skip_months(month, @date.day)).months | |
end | |
end | |
end | |
def calc_skip_months(month, day) | |
pos = MONTHS[day.to_s].find_index(month) | |
MONTHS[day.to_s][pos+1] - MONTHS[day.to_s][pos] | |
end | |
def set_date_to_current_day | |
get_advanced_date(@date.year == @advance_to_date.year) | |
end | |
def get_advanced_date(same_year) | |
case @schedule_option | |
when 'once' | |
@date | |
when 'daily' | |
@advance_to_date | |
when 'weekly' | |
@advance_to_date.next_occurring(@date.strftime("%A").downcase.to_sym) | |
when 'monthly' | |
skip_months = @advance_to_date.month - @date.month | |
new_date = @date + (skip_months).months | |
adavanced_date = if same_year | |
if (@date.day < @advance_to_date.day) | |
new_date.next_month | |
else | |
new_date | |
end | |
else | |
end | |
adavanced_date | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment