Sha256: 3d7a234bd7c8de9b5d360eeaacdec2de97fca139fec4133254f879f3f23cfe43

Contents?: true

Size: 1.28 KB

Versions: 5

Compression:

Stored size: 1.28 KB

Contents

require "montrose/rule"

module Montrose
  # Maintains stack of recurrences rules that apply to
  # an associated recurrence; manages advancing state
  # on each rule in stack as time instances are iterated.
  #
  class Stack
    def self.build(opts = {})
      [
        Frequency,
        Rule::After,
        Rule::Before,
        Rule::Total,
        Rule::TimeOfDay,
        Rule::HourOfDay,
        Rule::NthDayOfMonth,
        Rule::NthDayOfYear,
        Rule::DayOfWeek,
        Rule::DayOfMonth,
        Rule::DayOfYear,
        Rule::WeekOfYear,
        Rule::MonthOfYear
      ].map { |r| r.from_options(opts) }.compact
    end

    def initialize(opts = {})
      @stack = self.class.build(opts)
    end

    # Given a time instance, advances state of when all
    # recurrence rules on the stack match, and yielding
    # time to the block, otherwise, invokes break? on
    # non-matching rules.
    #
    # @param [Time] time - time instance candidate for recurrence
    #
    def advance(time)
      yes, no = @stack.partition { |rule| rule.include?(time) }

      if no.empty?
        yes.all? { |rule| rule.advance!(time) } or return false
        puts time if ENV["DEBUG"]
        yield time if block_given?
        true
      else
        no.any?(&:continue?)
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
montrose-0.2.2 lib/montrose/stack.rb
montrose-0.2.1 lib/montrose/stack.rb
montrose-0.2.0 lib/montrose/stack.rb
montrose-0.1.1 lib/montrose/stack.rb
montrose-0.1.0 lib/montrose/stack.rb