Class: Xml2js::Parser

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

Constant Summary collapse

DEFAULT_SCRIPT =
'./lib/xml2js/parser.js'

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(script) ⇒ Parser

Returns a new instance of Parser.



11
12
13
# File 'lib/xml2js/parser.rb', line 11

def initialize(script)
  @parser = script
end

Class Method Details

.parse(data, script = DEFAULT_SCRIPT) ⇒ Object



7
8
9
10
# File 'lib/xml2js/parser.rb', line 7

def self.parse(data, script=DEFAULT_SCRIPT)
  parser = new script
  parser.xml_to_hash data
end

Instance Method Details

#xml_to_hash(data) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/xml2js/parser.rb', line 15

def xml_to_hash(data)
  tmp_dir = "#{File.expand_path(__dir__)}/tmp"
  file = Tempfile.new(['xml-data', '.xml'], tmp_dir)
  json_file = Tempfile.new(['json-data', '.json'], tmp_dir)
  begin
    file.write(data)
    file.rewind
    json_file.rewind
    %x{ node #{@parser} #{file.path} #{json_file.path}}
    JSON.parse(File.read(json_file.path), {symbolize_names: true})
  ensure
    file.close
    file.unlink
  end
end