-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.rb
98 lines (79 loc) · 2.14 KB
/
parser.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
61
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
class LpString < String
def isKeyValuePair?
self.include? ':'
end
def isSection?
self[0] == '['
end
end
class Parser
attr_accessor :data, :filename
def initialize(filename)
@data = {}
@filename = filename
end
def parse
File.open(filename, "r") do |infile|
while (line = infile.gets)
line = LpString.new(line)
line.strip!
unless line.empty?
# chacking if line is a header
if line.isSection?
# convert "[ meta data ]" to "meta data"
section = line.gsub(/['\['\]]/,'').strip
else
# check if line is a key/value pair
if line.isKeyValuePair?
key_value = line.split(':')
section = section
key = key_value[0].strip
value = key_value[1].strip
add_data(section,key,value)
else
add_data(section,key,line)
end
end
end
end
end
end
def add_data(section,key,value)
if section.empty? || key.empty?
raise Exception, "Please enter valid section and key"
end
# check if section exists?
if @data.has_key?(section)
# check if section with key exists then append the value
if @data[section].has_key?(key)
value = get_data(section,key) + "\r #{value}"
end
@data[section].merge!({key => value})
else
@data[section] = {key => value}
end
end
def get_data(section,key)
if section.empty? || key.empty?
raise Exception, "Please enter valid section and key"
end
@data[section][key] if @data.has_key?(section)
end
def save_file(filename)
file = File.open(filename, "w")
@data.each do |section_name,section_values|
file.write "[#{section_name}]\n"
section_values.each do |k,v|
file.write "#{k}:#{v}\n"
end
file.write "\n"
end
end
end
parser = Parser.new("parser-test.txt")
parser.parse
parser.add_data('header','k1','k2')
parser.add_data('header1','k1','k2')
parser.get_data('header','k1')
parser.data # display data hash
parser.save_file('ripan.txt') #save data hash to file