Sha256: ff82f5c4ad21d2bd4f448c63576a92b18b0e8d6113125ecdccb56856df4f4042

Contents?: true

Size: 1.16 KB

Versions: 3

Compression:

Stored size: 1.16 KB

Contents

module Repeatable
  class Schedule
    def initialize(arg)
      case arg
      when Repeatable::Expression::Base
        @expression = arg
      when Hash
        @expression = Parser.call(arg)
      else
        fail(ParseError, "Can't build a Repeatable::Schedule from #{arg.class}")
      end
    end

    def occurrences(start_date, end_date)
      start_date = Date(start_date)
      end_date = Date(end_date)

      fail(ArgumentError, 'end_date must be equal to or after start_date') if end_date < start_date

      (start_date..end_date).select { |date| include?(date) }
    end

    def next_occurrence(start_date = Date.today, include_start: false, limit: 36525)
      date = Date(start_date)

      return date if include_start && include?(date)

      1.step do |i|
        date = date.next_day

        break date if include?(date)
        break if i == limit.to_i
      end
    end

    def include?(date = Date.today)
      date = Date(date)
      expression.include?(date)
    end

    def to_h
      expression.to_h
    end

    def ==(other)
      other.is_a?(self.class) && expression == other.expression
    end

    protected

    attr_reader :expression
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
repeatable-0.6.0 lib/repeatable/schedule.rb
repeatable-0.5.0 lib/repeatable/schedule.rb
repeatable-0.4.0 lib/repeatable/schedule.rb