Module: MicroConfig

Extended by:
MicroConfig
Included in:
MicroConfig
Defined in:
lib/micro_config/micro_config.rb,
lib/micro_config/version.rb

Overview

MicroConfig - support for a basic yaml configuration

Constant Summary collapse

VERSION =
'0.1.0'.freeze

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *arguments, &_block) ⇒ Object



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/micro_config/micro_config.rb', line 69

def method_missing(method, *arguments, &_block)
  clean_method = method.to_s

  case clean_method
  when /(.+)=$/
    key          = clean_method.delete('=').to_sym
    @config[key] = arguments.size == 1 ? arguments[0] : arguments
  when /(.+)\?$/
    key = clean_method.delete('?').to_sym

    @config.keys.include?(key)
  else
    key = clean_method.to_sym

    @config.fetch(key)
  end
end

Instance Method Details

#[](key) ⇒ Object



28
29
30
# File 'lib/micro_config/micro_config.rb', line 28

def [](key)
  @config[key]
end

#[]=(key, value) ⇒ Object



32
33
34
# File 'lib/micro_config/micro_config.rb', line 32

def []=(key, value)
  @config[key.to_sym] = symbolize(value)
end

#configure(source = nil, options = {}, &_block) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/micro_config/micro_config.rb', line 40

def configure(source = nil, options = {}, &_block)
  if options[:environment]
    case source
    when /\.(yml|yaml)$/i
      file_config        = YAML.load_file(source)
      environment_config = file_config.fetch(options[:environment].to_s)

      @config.merge!(symbolize(environment_config))
    when Hash
      hash_config = source.fetch(options[:environment].to_s)

      @config.merge!(symbolize(hash_config))
    else
      yield self if block_given?
    end
  else
    case source
    when /\.(yml|yaml)$/i
      @config.merge!(symbolize(YAML.load_file(source)))
    when Hash
      @config.merge!(symbolize(source))
    else
      yield self if block_given?
    end
  end
rescue => ce
  raise("Problems loading config source: #{source}: (#{ce.message})")
end

#fetch(key, default = nil) ⇒ Object



36
37
38
# File 'lib/micro_config/micro_config.rb', line 36

def fetch(key, default = nil)
  @config.fetch(key, default)
end

#symbolize(object) ⇒ Object



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

def symbolize(object)
  case object
  when Hash
    object.inject({}) do |memo, (k, v)|
      memo.tap { |m| m[k.to_sym] = symbolize(v) }
    end
  when Array
    object.map { |v| symbolize(v) }
  else
    object
  end
end

#to_hObject



24
25
26
# File 'lib/micro_config/micro_config.rb', line 24

def to_h
  @config
end