Class: Econfig::Configuration

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeConfiguration

Returns a new instance of Configuration.



7
8
9
10
# File 'lib/econfig/configuration.rb', line 7

def initialize
  @backends ||= BackendCollection.new
  @casts ||= {}
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/econfig/configuration.rb', line 47

def method_missing(name, *args)
  if respond_to?(name)
    raise ArgumentError, "too many arguments (#{args.length} for 0)" if args.length > 0
    if ::ENV["ECONFIG_PERMISSIVE"].to_s.empty?
      fetch(name)
    else
      self[name]
    end
  else
    super
  end
end

Instance Attribute Details

#backendsObject (readonly)

Returns the value of attribute backends.



5
6
7
# File 'lib/econfig/configuration.rb', line 5

def backends
  @backends
end

#castsObject (readonly)

Returns the value of attribute casts.



5
6
7
# File 'lib/econfig/configuration.rb', line 5

def casts
  @casts
end

#default_write_backendObject

Returns the value of attribute default_write_backend.



3
4
5
# File 'lib/econfig/configuration.rb', line 3

def default_write_backend
  @default_write_backend
end

Instance Method Details

#cast(key, &block) ⇒ Object



12
13
14
# File 'lib/econfig/configuration.rb', line 12

def cast(key, &block)
  casts[key.to_s] = block
end

#fetch(key) ⇒ Object



20
21
22
23
24
# File 'lib/econfig/configuration.rb', line 20

def fetch(key)
  get(key) do
    raise Econfig::NotFound, "configuration key '#{key}' is not set"
  end
end

#get(key) ⇒ Object Also known as: []



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

def get(key)
  key = key.to_s
  value = backends.get(key) do
    yield if block_given?
    return nil
  end
  value = casts[key].call(value) if casts[key]
  value
end

#keysObject



16
17
18
# File 'lib/econfig/configuration.rb', line 16

def keys
  backends.keys
end

#respond_to_missing?(name) ⇒ Boolean

Returns:

  • (Boolean)


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

def respond_to_missing?(name, *)
  name = name.to_s
  not(name.end_with?("=") or name.end_with?("!") or name.end_with?("?"))
end

#set(backend_name = default_write_backend, key, value) ⇒ Object Also known as: []=

Raises:

  • (ArgumentError)


37
38
39
40
41
42
43
44
# File 'lib/econfig/configuration.rb', line 37

def set(backend_name = default_write_backend, key, value)
  raise ArgumentError, "no backend given" unless backend_name
  if backend = backends[backend_name]
    backend.set(key.to_s, value)
  else
    raise KeyError, "#{backend_name} is not set"
  end
end