Class: Kanrisuru::Core::System::Parser::Sysctl

Inherits:
Object
  • Object
show all
Defined in:
lib/kanrisuru/core/system/parsers/sysctl.rb

Class Method Summary collapse

Class Method Details

.build_nested_hash(array, value) ⇒ Object



48
49
50
# File 'lib/kanrisuru/core/system/parsers/sysctl.rb', line 48

def build_nested_hash(array, value)
  array.reverse.inject(value) { |assigned_value, key| { key => assigned_value } }
end

.build_struct(hash) ⇒ Object



28
29
30
31
32
33
34
35
36
# File 'lib/kanrisuru/core/system/parsers/sysctl.rb', line 28

def build_struct(hash)
  struct = Struct.new(*hash.keys).new

  hash.each_key do |key|
    struct[key] = hash[key].is_a?(Hash) ? build_struct(hash[key]) : hash[key]
  end

  struct
end

.merge_recursively(h1, h2) ⇒ Object



38
39
40
41
42
43
44
45
46
# File 'lib/kanrisuru/core/system/parsers/sysctl.rb', line 38

def merge_recursively(h1, h2)
  h1.merge(h2) do |_k, v1, v2|
    if v1.is_a?(Hash) && v2.is_a?(Hash)
      merge_recursively(v1, v2)
    else
      [v1, v2].flatten
    end
  end
end

.parse(command) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/kanrisuru/core/system/parsers/sysctl.rb', line 11

def parse(command)
  result = {}

  lines = command.to_a
  lines.each do |line|
    next if line.include?('permission denied on key')

    keys, value = parse_line(line)
    next if Kanrisuru::Util.blank?(value)

    hash = build_nested_hash(keys, value)
    result = merge_recursively(result, hash)
  end

  build_struct(result)
end

.parse_line(line) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/kanrisuru/core/system/parsers/sysctl.rb', line 52

def parse_line(line)
  string, value = line.split(' =')
  return if Kanrisuru::Util.blank?(value)

  string = string.strip
  value = value.strip

  if Kanrisuru::Util.numeric?(value)
    value = value.to_i
  elsif /\t+/.match(value)
    ## Split tab delimited strings
    value = value.split(/\t/)
  end

  [string.split('.').map(&:to_sym), value]
end