Sha256: ae6b1ed7d80a9222639321e095f03091aacc5e0b35fe85011760976d35da2c79

Contents?: true

Size: 1.14 KB

Versions: 4

Compression:

Stored size: 1.14 KB

Contents

module TimeInterval
  class RepeatingInterval
    def self.parse(iso8601)
      recurrence, time_with_duration_string = iso8601.split('/', 2)

      times = if recurrence.match(/^R(\d+)/)
                Regexp.last_match[1].to_i
              else
                Float::INFINITY
              end

      fail ArgumentError if times == 0

      new TimeWithDuration.parse(time_with_duration_string), times
    end

    include Enumerable

    attr_reader :length

    def initialize(time_with_duration, times)
      @time_with_duration = time_with_duration
      @length = times
    end

    def each(&block)
      enumerator.each(&block)
    end

    def iso8601
      if length == Float::INFINITY
        "R/#{@time_with_duration.iso8601}"
      else
        "R#{length}/#{@time_with_duration.iso8601}"
      end
    end

    private

    def enumerator
      @enumerator ||= Enumerator::Lazy.new(0...length) do |yielder, i|
        if i == 0
          yielder.yield @time_with_duration
        else
          interval = @time_with_duration
          i.times { interval = interval.step }
          yielder.yield interval
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
time-interval-0.0.5 lib/time_interval/repeating_interval.rb
time-interval-0.0.4 lib/time_interval/repeating_interval.rb
time-interval-0.0.3 lib/time_interval/repeating_interval.rb
time-interval-0.0.2 lib/time_interval/repeating_interval.rb