Sha256: c30aeff19d5a32962bc5644a4c013282109dcd842fd7a947d133696a45c20b42

Contents?: true

Size: 1.88 KB

Versions: 2

Compression:

Stored size: 1.88 KB

Contents

require "nokogiri"

module SAXMachine
  
  def self.included(base)
    base.extend ClassMethods
  end
  
  def parse(xml_text)
    unless @parser
      sax_handler = SAXHandler.new(self)
      @parser = Nokogiri::XML::SAX::PushParser.new(sax_handler)
    end
    @parser << xml_text
    self
  end

  def parse_finish
    if @parser
      @parser.finish
    end
    self
  end
  
  module ClassMethods

    def parse(xml_text)
      # It might be cleaner to aditionally call parse_finish here, but
      # then Nokogiri/libxml2 barfs on incomplete documents. Desired
      # behaviour?
      new.parse(xml_text)
    end
    
    def element(name, options = {})
      options[:as] ||= name
      sax_config.add_top_level_element(name, options)
      
      # we only want to insert the getter and setter if they haven't defined it from elsewhere.
      # this is how we allow custom parsing behavior. So you could define the setter
      # and have it parse the string into a date or whatever.
      attr_reader options[:as] unless instance_methods.include?(options[:as].to_s)
      attr_writer options[:as] unless instance_methods.include?("#{options[:as]}=")
    end
    
    def elements(name, options = {})
      options[:as] ||= name
      if options[:class]
        sax_config.add_collection_element(name, options)
      else
        class_eval <<-SRC
          def add_#{options[:as]}(value)
            #{options[:as]} << value
          end
        SRC
        sax_config.add_top_level_element(name, options.merge(:collection => true))
      end
      
      if !instance_methods.include?(options[:as].to_s)
      class_eval <<-SRC
          def #{options[:as]}
            @#{options[:as]} ||= []
          end
        SRC
      end
      
      attr_writer options[:as] unless instance_methods.include?("#{options[:as]}=")
    end
    
    def sax_config
      @sax_config ||= SAXConfig.new
    end
  end
  
end

Version data entries

2 entries across 2 versions & 2 rubygems

Version Path
astro-sax-machine-0.0.12.20090419 lib/sax-machine/sax_document.rb
julien51-sax-machine-0.0.13 lib/sax-machine/sax_document.rb