Module: XMLHash

Defined in:
lib/lyrics/utils/xmlhash.rb

Class Method Summary collapse

Class Method Details

.read(file, hash, only_hash_keys = true) ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/lyrics/utils/xmlhash.rb', line 62

def XMLHash.read( file, hash, only_hash_keys=true )

  begin
    read_file = nil
    read_file = file.is_a?( File ) ? file : File.new( file, "r" )
    elements = REXML::Document.new( read_file ).root.elements
    return false if elements == nil
  rescue Exception => e
    return false
  ensure
    read_file.close() if read_file && read_file != file
  end

  requested_keys = hash.keys

  keys = hash.keys
  if ! only_hash_keys
    elements.each() do |element|
      key = element.name
      keys << key if ! keys.include?( key )
    end
  end

  read_keys = []
  keys.each() do |key|
    if elements[key]
      value = elements[key].text.to_s()
      type = elements[key].attribute( "type" ).to_s()
      if type == "array"
        hash[key] = value.split( "\n" )
      elsif ( type == "fixnum" )
        hash[key] = value.to_i()
      elsif ( type == "float" )
        hash[key] = value.to_f()
      elsif ( type == "trueclass" )
        hash[key] = true
      elsif ( type == "falseclass" )
        hash[key] = false
      else
        hash[key] = value
      end
      read_keys << key
    end
  end

  return (requested_keys - read_keys).empty?

end

.write(file, hash) ⇒ Object



23
24
25
26
27
28
29
30
31
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/lyrics/utils/xmlhash.rb', line 23

def XMLHash.write( file, hash )

  begin
    read_file = nil
    read_file = file.is_a?( File ) ? file : File.new( file, "r" )
    root = REXML::Document.new( read_file ).root
  rescue Exception
    root = REXML::Document.new( "<?xml version='1.0' encoding='UTF-8' ?>" ).add_element( "settings" )
  ensure
    read_file.close() if read_file
  end

  begin
    write_file = nil
    if ( file.is_a?( File ) )
      file.reopen( file.path, "w+" )
      write_file = file
    else
      write_file = File.new( file, "w+" )
    end
    hash.each do |key, value|
      element = root.elements[key]
      element = root.add_element( key ) if ! element
      element.text = value.is_a?( Array ) ? value.join( "\n" ) : value.to_s()
      element.add_attribute( "type", value.class.name.downcase )
    end
    root.parent.write( write_file )
    write_file.flush()
    return true
  rescue Exception => e
    puts e
    puts e.backtrace
    return false
  ensure
    write_file.close() if write_file != file
  end

end