Class: ConfigBase

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

Overview

The defaults for machinery’s configuration are defined in the file ‘machinery_config.rb’.

Direct Known Subclasses

Machinery::Config

Instance Method Summary collapse

Constructor Details

#initializeConfigBase

Returns a new instance of ConfigBase.



23
24
25
26
27
28
# File 'lib/config_base.rb', line 23

def initialize
  @entries = {}
  @file = ""
  define_entries
  apply_custom_config(@file) if File.exist?(@file)
end

Instance Method Details

#default_config_file(file) ⇒ Object



30
31
32
# File 'lib/config_base.rb', line 30

def default_config_file(file)
  @file = file
end

#define_entriesObject

Raises:

  • (NotImplementedError)


42
43
44
# File 'lib/config_base.rb', line 42

def define_entries
  raise NotImplementedError.new("No config entries defined for #{self.class}")
end

#each(&block) ⇒ Object



46
47
48
# File 'lib/config_base.rb', line 46

def each(&block)
  @entries.map { |key, value| [unnormalize_key(key), value] }.each(&block)
end

#entry(key, parameters = {}) ⇒ Object



34
35
36
37
38
39
40
# File 'lib/config_base.rb', line 34

def entry(key, parameters = {})
  key = normalize_key(key)

  @entries[key] = { value: parameters[:default], description: parameters[:description] }
   create_method(key.to_sym) { get(key) }
   create_method("#{key}=".to_sym) { |value| set(key, value) }
end

#get(key) ⇒ Object



50
51
52
53
54
55
# File 'lib/config_base.rb', line 50

def get(key)
  key = normalize_key(key)

  ensure_config_exists(key)
  @entries[key][:value]
end

#set(key, value, options = {auto_save: true}) ⇒ Object



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

def set(key, value, options = {auto_save: true} )
  key = normalize_key(key)
  ensure_config_exists(key)

  # Check if data type is correct. true and false are not of the same type which makes the check complex
  if value.class != @entries[key][:value].class &&
    ! ( ( value == true || value == false ) && ( @entries[key][:value].class == TrueClass || @entries[key][:value].class == FalseClass ) )
    raise Machinery::Errors::MachineryError.new("The value \"#{value}\" for configuration key \"#{key}\" is of an invalid data type.")
  end

  @entries[key][:value] = value

  save if options[:auto_save]
end