Class: BasicConfig

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

Defined Under Namespace

Classes: NotFound

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash, configuration_name = nil, configuration_scope = '') ⇒ BasicConfig

Returns a new instance of BasicConfig.

Raises:

  • (ArgumentError)


16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/basic_config.rb', line 16

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

  @name = configuration_name || "BasicConfig constructed at #{caller[0]}"
  @scope = configuration_scope

  # 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, @name, [@scope, key, '.'].join) 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



41
42
43
44
45
46
47
48
# File 'lib/basic_config.rb', line 41

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
    raise NotFound.new(@name, @scope, meth)
  end
end

Class Method Details

.load_env(name, env) ⇒ Object



66
67
68
# File 'lib/basic_config.rb', line 66

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

.load_file(name) ⇒ Object



62
63
64
# File 'lib/basic_config.rb', line 62

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

Instance Method Details

#[](key) ⇒ Object



33
34
35
# File 'lib/basic_config.rb', line 33

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

#include?(key) ⇒ Boolean

Returns:

  • (Boolean)


37
38
39
# File 'lib/basic_config.rb', line 37

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

#respond_to?(meth) ⇒ Boolean

Returns:

  • (Boolean)


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

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

#to_hashObject



54
55
56
57
58
59
60
# File 'lib/basic_config.rb', line 54

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