Module: Host::Hashifier

Included in:
Linux::Memory, Linux::Processor
Defined in:
lib/host/hashifier.rb

Overview

Module for parse a string containing data into a hash of values. Given a string and regular expression that parses and saves key and value, this module returns the built hash.

Used mainly to parse /proc/cpuinfo and /proc/meminfo files (and similars)

Instance Method Summary collapse

Instance Method Details

#hashify(data, options) ⇒ Object

Builds an array of hashes with the data passed, since duplicate keys cause another entry to be stored in the array returned (as it was a representation of many resources of the same type).

Note: the way it is implemented, you can pass not only a Ruby Array, but any object that responds to <<

Example:

cpu = File.read('/proc/cpuinfo')
hashify(cpu, :regexp => /your regexp here/, :into => @cpu_info)


23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/host/hashifier.rb', line 23

def hashify(data, options)
  regexp = options[:regexp]
  dest   = options[:into]

  info = {}

  data.each_line { |line|
    matches = line.match(regexp)
    next if matches.nil?

    if info.has_key?(matches[1].strip.to_sym)
      dest << info
      info = {}
    else
      info[matches[1].strip.to_sym] = matches[2]
    end
  }

  dest << info
  
end