Sha256: 7caadf4cfdef19f0ac5dcc7dd17e2f9b7d9fc09912c9523dfe7fd0bcf02a992c

Contents?: true

Size: 1.73 KB

Versions: 1

Compression:

Stored size: 1.73 KB

Contents

module IcalImporter
  class Parser
    attr_reader :feed, :bare_feed, :url

    def initialize(url)
      @url = url
      @bare_feed = open_ical
      if should_parse?
        @bare_feed.pos = 0
        @feed = RiCal.parse @bare_feed
      end
    end

    def should_parse?
      bare_feed.present?
    end

    def worth_parsing?
      should_parse? && feed.present? && feed.first
    end

    def all_events(&block)
      tap_and_each (@imported_single_events || []) + (@imported_recurrence_events || []), &block
    end

    def single_events(&block)
      tap_and_each (@imported_single_events || []), &block
    end

    def recurrence_events(&block)
      tap_and_each (@imported_recurrence_events || []), &block
    end

    def parse(&block)
      if worth_parsing?
        collected = Collector.new(feed.first.events).collect
        @imported_single_events = collected.single_events
        @imported_recurrence_events = collected.recurrence_events
        tap_and_each (@imported_single_events + @imported_recurrence_events), &block
      end
    end

    private

    def tap_and_each(list)
      list.tap do |r|
        r.each do |event|
          yield event if block_given?
        end
      end
    end

    def open_ical(protocol = 'http')
      raise ArgumentError, "Must be http or https" unless %w[http https].include? protocol
      begin
        Timeout::timeout(5) do
          open prepped_uri(protocol)
        end
      rescue
        return open_ical 'https' if protocol == 'http'
        nil
      end
    end

    def prepped_uri(protocol)
      uri = url.strip.gsub(/^[Ww]ebcal:/, "#{protocol}:")
      uri = begin
              URI.unescape(uri)
            rescue URI::InvalidURIError
            end
      URI.escape(uri)
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ical_importer-0.0.1 lib/ical_importer/parser.rb