Class: SAXMachine::SAXHandler

Inherits:
Nokogiri::XML::SAX::Document
  • Object
show all
Defined in:
lib/sax-machine/sax_handler.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object) ⇒ SAXHandler

Returns a new instance of SAXHandler.



7
8
9
10
# File 'lib/sax-machine/sax_handler.rb', line 7

def initialize(object)
  @stack = [[object, nil, ""]]
  @parsed_configs = {}
end

Instance Attribute Details

#stackObject (readonly)

Returns the value of attribute stack.



5
6
7
# File 'lib/sax-machine/sax_handler.rb', line 5

def stack
  @stack
end

Instance Method Details

#characters(string) ⇒ Object Also known as: cdata_block



12
13
14
15
# File 'lib/sax-machine/sax_handler.rb', line 12

def characters(string)
  object, config, value = stack.last
  value << string
end

#end_element(name) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/sax-machine/sax_handler.rb', line 40

def end_element(name)
  (object, _, _), (element, config, value) = stack[-2..-1]
  return unless config && config.name.to_s == name.to_s

  unless parsed_config?(object, config)
    if config.respond_to?(:accessor)
      object.send(config.accessor) << element
    else
      value = config.data_class ? element : value
      object.send(config.setter, value) unless value == ""
      mark_as_parsed(object, config)
    end
  end
  stack.pop
end

#mark_as_parsed(object, element_config) ⇒ Object



56
57
58
# File 'lib/sax-machine/sax_handler.rb', line 56

def mark_as_parsed(object, element_config)
  @parsed_configs[[object.object_id, element_config.object_id]] = true unless element_config.collection?
end

#parsed_config?(object, element_config) ⇒ Boolean

Returns:

  • (Boolean)


60
61
62
# File 'lib/sax-machine/sax_handler.rb', line 60

def parsed_config?(object, element_config)
  @parsed_configs[[object.object_id, element_config.object_id]]
end

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



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/sax-machine/sax_handler.rb', line 18

def start_element(name, attrs = [])
  object, config, value = stack.last
  return unless object.class.respond_to?(:sax_config)
  
  sax_config = object.class.sax_config
  attrs.flatten!

  if collection_config = sax_config.collection_config(name, attrs)
    stack.push [object = collection_config.data_class.new, collection_config, ""]
    object, sax_config = object, object.class.sax_config
  end
  sax_config.element_configs_for_attribute(name, attrs).each do |ec|
    unless parsed_config?(object, ec)
      object.send(ec.setter, ec.value_from_attrs(attrs))
      mark_as_parsed(object, ec)
    end
  end
  if !collection_config && ec = sax_config.element_config_for_tag(name, attrs)
    stack.push [ec.data_class ? ec.data_class.new : object, ec, ""]
  end
end