Employ File.expand_path as appropriate
[amazing.git] / lib / amazing / proc_file.rb
blobb0ededf330c40a4c123a0439a51218a243bdeb03
1 # Copyright (C) 2008 Dag Odenhall <dag.odenhall@gmail.com>
2 # Licensed under the Academic Free License version 3.0
4 module Amazing
6   # Parse a /proc file
7   #
8   #   cpuinfo = ProcFile.parse_file("cpuinfo")
9   #   cpuinfo[1]["model name"]
10   #   #=> "AMD Turion(tm) 64 X2 Mobile Technology TL-50"
11   class ProcFile
12     include Enumerable
14     def self.parse_file(file)
15       file = File.expand_path(file, "/proc")
16       new(File.new(file))
17     end
19     def initialize(string_or_io)
20       case string_or_io
21       when String
22         content = string_or_io
23       when IO
24         content = string_or_io.read
25         string_or_io.close
26       end
27       @list = [{}]
28       content.each_line do |line|
29         if sep = line.index(":")
30           @list[-1][line[0..sep-1].strip] = line[sep+1..-1].strip
31         else
32           @list << {}
33         end
34       end
35       @list.pop if @list[-1].empty?
36     end
38     def each
39       @list.each do |section|
40         yield section
41       end
42     end
44     def [](section)
45       @list[section]
46     end
47   end
48 end