Class: SergioSax

Inherits:
Nokogiri::XML::SAX::Document
  • Object
show all
Defined in:
lib/sergio/sergio_sax.rb

Instance Method Summary collapse

Constructor Details

#initialize(object) ⇒ SergioSax

Returns a new instance of SergioSax.



2
3
4
5
6
7
# File 'lib/sergio/sergio_sax.rb', line 2

def initialize(object)
  @stack = []
  @object = object
  @current_configs = []
  @parent_callbacks = []
end

Instance Method Details

#cdata_block(string) ⇒ Object



28
29
30
# File 'lib/sergio/sergio_sax.rb', line 28

def cdata_block(string)
  characters(string)
end

#characters(string) ⇒ Object



23
24
25
26
# File 'lib/sergio/sergio_sax.rb', line 23

def characters(string)
  name, attrs = @stack.last
  attrs['@text'] = attrs.fetch('@text', '') + string
end

#end_element(name) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/sergio/sergio_sax.rb', line 32

def end_element(name)
  current_configs = @object.class.sergio_config.get_element_configs(@stack)
  name, attrs = @stack.pop
  if current_configs
    current_configs.each do |c|
      attr = c.options[:attribute]
      val = attrs[attr]
      callback = c.callback

      if val && !c.aggregate_element
        r = if callback.arity == 1
          callback.call(val)
        elsif callback.arity == 2
          attrs.delete('@text')
          callback.call(val, attrs)
        end

        #only builds parent elements if at least one of their child elements has a match
        @parent_callbacks.each do |c|
          c.call
        end
        @parent_callbacks = []

        #build an array of hashes if return value from callback is a hash
        @object.sergio_parsed_document.set_element(c.new_path, {}, c.options) if r.is_a?(Hash)
        @object.sergio_parsed_document.set_element(c.new_path, r, c.options)
      end
    end
  end
  @parent_callbacks = []
end

#start_element(name, attrs = []) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/sergio/sergio_sax.rb', line 9

def start_element(name, attrs = [])
  attrs = Hash[*attrs.flatten]
  @stack << [name, attrs]
  if current_configs = @object.class.sergio_config.get_element_configs(@stack)
    current_configs.each do |c|
      if c.aggregate_element
        @parent_callbacks << lambda do
          @object.sergio_parsed_document.set_element(c.new_path, {}, c.options)
        end
      end
    end
  end
end