Sha256: 529d4ab0e71ae78ab9af46ae6da592df48408159e09e2fa9e54a0d35c765292a

Contents?: true

Size: 1.85 KB

Versions: 11

Compression:

Stored size: 1.85 KB

Contents

module Feedzirra
  class NoParserAvailable < StandardError; end
  
  # Determines the correct parser for an XML feed.
  class FeedParser
    attr_reader :xml, :parser
    
    def initialize(xml)
      @xml    = xml
      @parser = detect_feed_processor_for_xml(@xml)
    end
    
    def detect_feed_processor_for_xml(xml)
      start_of_doc = xml.slice(0, 1000)

      if_none_found = lambda do
        raise NoParserAvailable.new("No valid parser for XML.")
      end

      feed_classes.detect(if_none_found) do |klass| 
        klass.able_to_parse?(start_of_doc)
      end    
    end
    
    # Determines the correct Parser for the XML document with which
    # we were initialized and returns results of this parser on the 
    # document.  Raises NoParserAvailable if no valid parser is 
    # found.
    def run
      @parser.parse(@xml)
    end

    # Adds a new feed parsing class that will be used for parsing.
    #
    # === Parameters
    # [klass<Constant>] The class/constant that you want to register.
    # === Returns
    # A updated array of feed parser class names.
    def add_feed_class(klass) 
      feed_classes.unshift klass
    end

    # Provides a list of registered feed parsing classes.
    #
    # === Returns
    # A array of class names.
    def feed_classes
      @@feed_classes ||= [Feedzirra::Parser::RSS, Feedzirra::Parser::AtomFeedBurner, Feedzirra::Parser::Atom]
    end
    
    # Makes all entry types look for the passed in element to parse. This is actually just a call to 
    # element (a SAXMachine call) in the class
    #
    # === Parameters
    # [element_tag<String>]
    # [options<Hash>] Valid keys are same as with SAXMachine
    def add_common_feed_entry_element(element_tag, options = {})
      feed_classes.map{|k| eval("#{k}Entry") }.each do |klass|
        klass.send(:element, element_tag, options)
      end
    end
    
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
jsl-feedzirra-0.0.12.1 lib/feedzirra/feed_parser.rb
jsl-feedzirra-0.0.12.10 lib/feedzirra/feed_parser.rb
jsl-feedzirra-0.0.12.12 lib/feedzirra/feed_parser.rb
jsl-feedzirra-0.0.12.2 lib/feedzirra/feed_parser.rb
jsl-feedzirra-0.0.12.3 lib/feedzirra/feed_parser.rb
jsl-feedzirra-0.0.12.4 lib/feedzirra/feed_parser.rb
jsl-feedzirra-0.0.12.5 lib/feedzirra/feed_parser.rb
jsl-feedzirra-0.0.12.6 lib/feedzirra/feed_parser.rb
jsl-feedzirra-0.0.12.7 lib/feedzirra/feed_parser.rb
jsl-feedzirra-0.0.12.8 lib/feedzirra/feed_parser.rb
jsl-feedzirra-0.0.12.9 lib/feedzirra/feed_parser.rb