Sha256: 41c3c4cade87b21f170c98d8e97bcfa694db15ef3454f4ee1a261e3418ad6eed

Contents?: true

Size: 1.2 KB

Versions: 3

Compression:

Stored size: 1.2 KB

Contents

require "nokogiri"

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

    def parse(xml_text)
      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 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.
      if instance_methods.include?("#{options[:as]}=")
        attr_reader options[:as]
      else
        attr_accessor options[:as]
      end
    end
    
    def elements(name, options = {})
      options[:as] ||= name
      sax_config.add_collection_element(name, options)
      
      class_eval <<-SRC
        def #{options[:as]}
          @#{options[:as]} ||= []
        end
      SRC
      
      attr_writer options[:as]
    end
    
    def sax_config
      @sax_config ||= SAXConfig.new
    end
  end
  
end

Version data entries

3 entries across 3 versions & 2 rubygems

Version Path
ealdent-sax-machine-0.0.7 lib/sax-machine/sax_document.rb
pauldix-sax-machine-0.0.6 lib/sax-machine/sax_document.rb
pauldix-sax-machine-0.0.7 lib/sax-machine/sax_document.rb