Class: BasicConfig

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash) ⇒ BasicConfig

Returns a new instance of BasicConfig.

Raises:

  • (ArgumentError)


4
5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/basic_config.rb', line 4

def initialize(hash)
  raise ArgumentError, 'Hash can not be nil' if hash.nil?

  # Symbolize keys: don't want to add ActiveSupport dependency just for this.
  @hash = hash.inject({}) do |h, (key, value)|
    h[key.to_sym] = value
    h
  end

  @hash.each do |key, value|
    @hash[key] = BasicConfig.new(value) if value.is_a?(Hash)
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



26
27
28
29
30
31
32
33
# File 'lib/basic_config.rb', line 26

def method_missing(meth, *args, &block)
  if include?(meth)
    raise ArgumentError, 'Getter can not receive any arguments' if !args.empty? || block_given?
    @hash[meth]
  else
    super
  end
end

Class Method Details

.load_env(name, env) ⇒ Object



51
52
53
# File 'lib/basic_config.rb', line 51

def self.load_env(name, env)
  BasicConfig.new(YAML.load_file(name)[env])
end

.load_file(name) ⇒ Object



47
48
49
# File 'lib/basic_config.rb', line 47

def self.load_file(name)
  BasicConfig.new(YAML.load_file(name))
end

Instance Method Details

#[](key) ⇒ Object



18
19
20
# File 'lib/basic_config.rb', line 18

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

#include?(key) ⇒ Boolean

Returns:

  • (Boolean)


22
23
24
# File 'lib/basic_config.rb', line 22

def include?(key)
  @hash.has_key?(key)
end

#respond_to?(meth) ⇒ Boolean

Returns:

  • (Boolean)


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

def respond_to?(meth)
  include?(meth) or super
end

#to_hashObject



39
40
41
42
43
44
45
# File 'lib/basic_config.rb', line 39

def to_hash
  @hash.dup.tap do |h|
    h.each do |key, value|
      h[key] = value.to_hash if value.is_a?(BasicConfig)
    end
  end
end