Class: Ox::Mapper::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/ox/mapper/parser.rb

Overview

Configurable SAX-parser

Usage:

parser = Mapper.new

parser.on(:offer) { |offer| puts offer }
parser.on(:offer => [:id]) { |v| v.to_i }

Instance Method Summary collapse

Constructor Details

#initializeParser

Returns a new instance of Parser.



15
16
17
# File 'lib/ox/mapper/parser.rb', line 15

def initialize
  @handler = Handler.new
end

Instance Method Details

#collect_attribute(map) ⇒ Object Also known as: on_attribute

Deprecated.

Set attribute callback

Examples:

parser.collect_attribute(:offer => :id, 'ns:offer' => 'ns:id')

Parameters:

  • map (Hash{String, Symbol => String, Symbol})

    hash with element names as keys and attributes names as value



55
56
57
58
59
60
61
62
# File 'lib/ox/mapper/parser.rb', line 55

def collect_attribute(map)
  warn 'Ox::Mapper::Parser#on_attribute method is deprecated and shall be removed in future versions. '\
       'Please use #on(element_name, :attributes => [...]) notation.'

  map.each_pair do |k, attributes|
    Array(attributes).flatten.each { |attr| @handler.collect_attribute(k, attr) }
  end
end

#on(*elements) {|element| ... } ⇒ Object Also known as: on_element

Define a callbacks to be called when elements processed

Examples:

parser.on(:offer, :price) { |elem| p elem }
parser.on(:book, :attributes => [:author, :isbn]) { |book| p book[:author], book[:isbn] }

Parameters:

  • elements (Array<String, Symbol>)

    elements names

  • options (Hash)

    a customizable set of options

Yields:

  • (element)

Yield Parameters:



34
35
36
37
38
39
40
41
42
43
44
# File 'lib/ox/mapper/parser.rb', line 34

def on(*elements, &block)
  options = (Hash === elements.last) ? elements.pop : {}

  attributes = Array(options[:attributes]).flatten

  elements.each do |e|
    @handler.setup_element_callback(e, block)

    attributes.each { |attr| @handler.collect_attribute(e, attr) }
  end
end

#parse(io, options = {}) ⇒ Object

Parse given io object



20
21
22
# File 'lib/ox/mapper/parser.rb', line 20

def parse(io, options = {})
  Ox.sax_parse(@handler, io, options)
end