Class: Cda::XmlParser

Inherits:
Object
  • Object
show all
Defined in:
lib/cda/xml_parser.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(xml, registry) ⇒ XmlParser

Returns a new instance of XmlParser.



6
7
8
9
# File 'lib/cda/xml_parser.rb', line 6

def initialize(xml, registry)
  @registry = registry
  @xml = xml
end

Instance Attribute Details

#registryObject

Returns the value of attribute registry.



3
4
5
# File 'lib/cda/xml_parser.rb', line 3

def registry
  @registry
end

#xmlObject (readonly)

Returns the value of attribute xml.



4
5
6
# File 'lib/cda/xml_parser.rb', line 4

def xml
  @xml
end

Instance Method Details

#parse(model_class = nil) ⇒ Object



11
12
13
# File 'lib/cda/xml_parser.rb', line 11

def parse(model_class = nil)
  instantiate_from_element(model_class || resolve_class)
end

#value_of(node_or_xpath, opts = {}) ⇒ 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
# File 'lib/cda/xml_parser.rb', line 32

def value_of(node_or_xpath, opts = {})
  if node_or_xpath.is_a?(String)
    node_set = xml.xpath(node_or_xpath)
    return if node_set.blank?
    if node_set.length > 1
      raise "Expected only one node as result of #{node_or_xpath}, but #{node_set.inspect}"
    end
    node = node_set.first
  else
    node = node_or_xpath
  end

  case opts[:as]
    when :numeric
      parse_numeric(node)
    when :boolean
      parse_boolean(node)
    when :datetime, :date
      parse_time(node)
    when :coded_value
      parse_coded_value(node)
    when :time_interval
      parse_time_interval(node)
    when :value_with_unit
      parse_value_with_unit(node)
    else
      node.text if node.present?
  end
end

#values_of(xpath, opts = {}) ⇒ Object



62
63
64
# File 'lib/cda/xml_parser.rb', line 62

def values_of(xpath, opts = {})
  xml.xpath(xpath).map { |node| value_of(node, opts) }
end

#within(*args) ⇒ Object



22
23
24
25
26
27
28
29
30
# File 'lib/cda/xml_parser.rb', line 22

def within(*args)
  xpath_or_node, xpath = args
  node = xpath_or_node.is_a?(String) ? xml.xpath(xpath_or_node) : xpath_or_node
  node = node.xpath(xpath) if xpath
  saved_node, @xml = @xml, node
  yield if @xml.present?
ensure
  @xml = saved_node
end

#within_each(xpath_or_nodes, &block) ⇒ Object



15
16
17
18
19
20
# File 'lib/cda/xml_parser.rb', line 15

def within_each(xpath_or_nodes, &block)
  nodes = xpath_or_nodes.is_a?(String) ? xml.xpath(xpath_or_nodes) : xpath_or_nodes
  nodes.each do |node|
    within(node, &block)
  end
end