Module: ConfigDSL::Memory

Defined in:
lib/configdsl.rb

Defined Under Namespace

Classes: MemoryLayer

Class Method Summary collapse

Class Method Details

.add_layer(new_layer, context) ⇒ Object

Adds a new layer if it does not exist



90
91
92
93
# File 'lib/configdsl.rb', line 90

def add_layer(new_layer, context)
  current_layer = expand_context(context)
  current_layer[new_layer] ||= layers_factory
end

.dataObject

Main data container



55
56
57
# File 'lib/configdsl.rb', line 55

def data
  @data ||= layers_factory
end

.expand_context(context) ⇒ Object

Return a layer described by context or rises an exception if any of parent layers is undefined



83
84
85
86
87
# File 'lib/configdsl.rb', line 83

def expand_context(context)
  context.inject(data) do |hash, level|
    hash[level]
  end
end

.fetch(key, defaul_value = nil, context = []) ⇒ Object

Fetches a specified key for a specified context Allows to provide a default value



67
68
69
70
71
# File 'lib/configdsl.rb', line 67

def fetch(key, defaul_value = nil, context = [])
  fetch!(key, context)
rescue KeyError => e
  defaul_value
end

.fetch!(key, context = []) ⇒ Object

Fetches a specified key for a specified context Raises exception if something goes wrong

Raises:

  • (KeyError)


75
76
77
78
79
# File 'lib/configdsl.rb', line 75

def fetch!(key, context = [])
  layer = expand_context(context)
  raise KeyError, "In context #{context} key not found: #{key.inspect}" unless layer.has_key?(key)
  layer[key]
end

.layers_factoryObject

Creates a new layer-level storage element



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

def layers_factory
  @factory_base_class ||= MemoryLayer
  @factory_base_class.new
end

.store(key, value, context = []) ⇒ Object

Stores a value in specified key for specified context



60
61
62
63
# File 'lib/configdsl.rb', line 60

def store(key, value, context = [])
  layer = expand_context(context)
  layer[key] = value
end