Class: LxcSsh::ContainerConfig

Inherits:
Object
  • Object
show all
Defined in:
lib/lxc_ssh/container_config.rb

Instance Method Summary collapse

Constructor Details

#initialize(data) ⇒ ContainerConfig

Loads the configuration object with the config files’ content

Parameters:

  • data (String)

    config file contents



7
8
9
# File 'lib/lxc_ssh/container_config.rb', line 7

def initialize(data)
  @content = parse(data)
end

Instance Method Details

#[](key) ⇒ Object

Array-style accessor (getter)

Parameters:

  • key (String)

    key of the hash

Returns:

  • (Object)


47
48
49
50
51
52
53
# File 'lib/lxc_ssh/container_config.rb', line 47

def [](key)
  if key.kind_of?(String) == false
    raise ArgumentError, 'key must be a string'
  end

  @content[key]
end

#[]=(key, val) ⇒ Object

Array-style accessor (setter)

Parameters:

  • key (String)

    key of the hash

  • val (Object)

    value to set



59
60
61
# File 'lib/lxc_ssh/container_config.rb', line 59

def []=(key, val)
  @content[key] = val
end

#config_contentsHash

Generates a config string from the current object context

Returns:

  • (Hash)


66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/lxc_ssh/container_config.rb', line 66

def config_contents
  lines = []

  @content.each_pair do |key, value|
    if value.class == Array
      # multiple values assigned for a single key, order is important!
      lines << value.map do |val|
        key + ' = ' + val
      end
    else
      line = key + ' = ' + value
      lines << line
    end
  end

  lines.join('\n')
end

#parse(data) ⇒ Hash

Loads the configuration object with the config files’ content

Parameters:

  • data (String)

    config file contents

Returns:

  • (Hash)


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
# File 'lib/lxc_ssh/container_config.rb', line 15

def parse(data)
  items = {}

  # only lines starting with 'lxc.'
  lines = data.lines.map(&:strip).select do |line|
    line.start_with?('lxc.')
  end

  # process lines
  lines.each do |line|
    key, value = line.split('=').map(&:strip)

    if items.key?(key) == false
      items[key] = []
    end

    items[key] << value
  end

  items.each_pair do |key, val|
    if val.length == 1
      items[key] = val.first
    end
  end

  items
end