Class: Chemicals::Parser

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

Instance Method Summary collapse

Constructor Details

#initialize(template) ⇒ Parser

Returns a new instance of Parser.



3
4
5
# File 'lib/chemicals/parser.rb', line 3

def initialize template
  @template = template
end

Instance Method Details

#parse(source) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/chemicals/parser.rb', line 7

def parse source
  @namespaces = {}
  # get the document in nokogiri without blanks
  # or if the source is already a nokogiri node, then assume it is without blanks.
  root = if source.kind_of? Nokogiri::XML::Node
    source.document.root
  else
    Nokogiri::XML(source.to_s) { |c| c.noblanks }.root
  end
  # delete all default namespaces and map the new ones in @namespaces
  handle_namespace root
  # map to a general namespace prefix => href hash
  @namespaces = Hash[(@namespaces.values + root.namespace_definitions).map { |ns|
    [ns.prefix, ns.href] if ns.prefix
  }]
  # begin parsing with the root node
  parse_node root, @template.for(root.path, @namespaces)
end