Class: Kplay::Config

Inherits:
Object
  • Object
show all
Defined in:
lib/kplay/config.rb

Overview

Represents the global or local configuration

Constant Summary collapse

GLOBAL_CONFIG_FILENAME =
'config'
GLOBAL_DEFAULTS =
{
  'image' => 'dev',
  'mount_path' => '/${name}',
  'shell' => '/bin/bash',
  'shell_args' => ['-c', 'cd /${name}; exec "${SHELL:-sh}"'],
  'stop_grace_period' => 5,
  'etc_hosts' => [], # <ip> <alias1> [<alias2> ...],
  'volumes' => [] # ["<from>:<to>", ...]
}.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data = {}, path = nil) ⇒ Config

Returns a new instance of Config.



22
23
24
25
26
27
# File 'lib/kplay/config.rb', line 22

def initialize(data = {}, path = nil)
  @path = path ? Pathname.new(path).expand_path : nil
  @data = data.dup
  @extra_data = YAML.load(File.read(path)) if path && File.exist?(path)
  @data = @data.merge(@extra_data) if @extra_data
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



20
21
22
# File 'lib/kplay/config.rb', line 20

def data
  @data
end

#pathObject (readonly)

Returns the value of attribute path.



20
21
22
# File 'lib/kplay/config.rb', line 20

def path
  @path
end

Class Method Details

.expand_template(text, vars) ⇒ Object

Expand templates in given string value.

Example:

"${name}" -> "my-pod"

Parameters:

  • text (String)
  • vars (Hash)


69
70
71
72
73
# File 'lib/kplay/config.rb', line 69

def self.expand_template(text, vars)
  vars.keys.reduce(text) do |t, var_name|
    t.gsub("${#{var_name}}", vars[var_name].to_s)
  end
end

.expand_templates!(hash, vars) ⇒ Object

In-place expansion of templates. Templates found in values are substituted with given vars



48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/kplay/config.rb', line 48

def self.expand_templates!(hash, vars)
  hash.keys.each do |key|
    case hash[key]
    when String
      hash[key] = expand_template(hash[key], vars)
    when Array
      hash[key] = hash[key].map { |t| expand_template(t, vars) }
    when Hash
      expand_templates!(hash[key], vars)
    end
  end
end

.globalObject



75
76
77
# File 'lib/kplay/config.rb', line 75

def self.global
  new(GLOBAL_DEFAULTS.dup, Kplay.data_path(GLOBAL_CONFIG_FILENAME))
end

.localObject



79
80
81
# File 'lib/kplay/config.rb', line 79

def self.local
  new(global.data, Pathname.pwd.join('.kplay'))
end

Instance Method Details

#[](key) ⇒ Object



29
30
31
32
33
# File 'lib/kplay/config.rb', line 29

def [](key)
  value = data[key.to_s]
  value = self.class.new(value) if value.is_a?(Hash)
  value
end

#expand_templates!(vars) ⇒ Object

Expands templates in the values of the current config.



41
42
43
# File 'lib/kplay/config.rb', line 41

def expand_templates!(vars)
  self.class.expand_templates!(@data, vars)
end

#to_hObject



35
36
37
# File 'lib/kplay/config.rb', line 35

def to_h
  data.dup
end