mirror of
https://github.com/plashchynski/crono.git
synced 2026-04-10 11:23:50 +02:00
Added 'on' option for Period
This commit is contained in:
@@ -1,19 +1,20 @@
|
||||
module Crono
|
||||
# Period describe frequency of performing a task
|
||||
class Period
|
||||
def initialize(period, at: nil)
|
||||
DAYS = [:monday, :tuesday, :wednesday, :thursday, :friday, :saturday,
|
||||
:sunday]
|
||||
|
||||
def initialize(period, at: nil, on: nil)
|
||||
@period = period
|
||||
@at_hour, @at_min = parse_at(at) if at
|
||||
@on = parse_on(on) if on
|
||||
end
|
||||
|
||||
def next(since: nil)
|
||||
if since.nil?
|
||||
@next = Time.now.change(time_atts)
|
||||
return @next if @next.future?
|
||||
since = Time.now
|
||||
end
|
||||
|
||||
@period.since(since).change(time_atts)
|
||||
return initial_next unless since
|
||||
@next = @period.since(since)
|
||||
@next = @next.beginning_of_week.advance(days: @on) if @on
|
||||
@next.change(time_atts)
|
||||
end
|
||||
|
||||
def description
|
||||
@@ -22,6 +23,28 @@ module Crono
|
||||
desc
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def initial_next
|
||||
next_time = initial_day.change(time_atts)
|
||||
return next_time if next_time.future?
|
||||
@period.from_now.change(time_atts)
|
||||
end
|
||||
|
||||
def initial_day
|
||||
return Time.now unless @on
|
||||
day = Time.now.beginning_of_week.advance(days: @on)
|
||||
return day if day.future?
|
||||
@period.from_now.beginning_of_week.advance(days: @on)
|
||||
end
|
||||
|
||||
def parse_on(on)
|
||||
day_number = DAYS.index(on)
|
||||
fail "Wrong 'on' day" unless day_number
|
||||
fail "period should be at least 1 week to use 'on'" if @period < 1.week
|
||||
day_number
|
||||
end
|
||||
|
||||
def parse_at(at)
|
||||
case at
|
||||
when String
|
||||
@@ -34,8 +57,6 @@ module Crono
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def time_atts
|
||||
{ hour: @at_hour, min: @at_min }.compact
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user