Class: Indocker::Configs::Config

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

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object



72
73
74
# File 'lib/indocker/configs/config.rb', line 72

def method_missing(method, *args, &block)
  raise "Undefined keyword #{method.inspect} for Indocker configuration file"
end

Instance Method Details

#cast_class_to_type(value) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/indocker/configs/config.rb', line 57

def cast_class_to_type(value)
  case value
  when Proc
    cast_class_to_type(value.call)
  when TrueClass
    :boolean
  when FalseClass
    :boolean
  when Indocker::Configs::Config
    :config
  else
    Indocker::StringUtils.underscore(value.class.name).to_sym
  end
end

#config(name, group: :default, &block) ⇒ Object



25
26
27
28
29
30
31
# File 'lib/indocker/configs/config.rb', line 25

def config(name, group: :default, &block)
  subconfiguration = Indocker::Configs::Config.new
  subconfiguration.instance_exec(&block)
  
  option(name, group: group, type: :config)
  send(name, subconfiguration)
end

#option(name, group: :default, type: :string) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/indocker/configs/config.rb', line 11

def option(name, group: :default, type: :string)
  define_singleton_method(name) do |value = nil, &block|
    write_value = block || value

    if write_value
      validate!(name, write_value, type)

      write_setting(name, write_value, group)
    else
      read_setting(name)
    end
  end
end

#read_setting(key) ⇒ Object



33
34
35
36
37
# File 'lib/indocker/configs/config.rb', line 33

def read_setting(key)
  read_value = scope[key.to_s][:value]
  
  read_value.is_a?(Proc) ? read_value.call : read_value
end

#scope ⇒ Object



3
4
5
# File 'lib/indocker/configs/config.rb', line 3

def scope
  @scope ||= Hash.new({})
end

#set(&block) ⇒ Object



7
8
9
# File 'lib/indocker/configs/config.rb', line 7

def set(&block)
  instance_exec(&block)
end

#validate!(name, value, type) ⇒ Object



46
47
48
49
50
51
52
53
54
55
# File 'lib/indocker/configs/config.rb', line 46

def validate!(name, value, type)
  value_type = cast_class_to_type(value)

  if type != value_type
    raise Indocker::Errors::ConfigOptionTypeMismatch, 
      "Expected option #{name.inspect} => #{value.inspect} to be a #{type.inspect}, not a #{value_type.inspect}"
  end

  nil
end

#write_setting(key, value, group) ⇒ Object



39
40
41
42
43
44
# File 'lib/indocker/configs/config.rb', line 39

def write_setting(key, value, group)
  scope[key.to_s] = {
    value: value,
    group: group
  }
end