Class: Sonia::Config

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

Overview

Simple configuration class

Examples:

"Config.new({:name => "Piotr"}).piotr" #=> "Piotr"

Instance Method Summary collapse

Constructor Details

#initialize(data = {}) ⇒ Config

Returns a new instance of Config.

Parameters:

  • data (Hash) (defaults to: {})

    Hash containing configuration data


8
9
10
11
# File 'lib/sonia/config.rb', line 8

def initialize(data={})
  @data = {}
  update!(data)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sym, *args) ⇒ Object

Returns configuration value by missing method name

Parameters:

  • sym (Symbol)

    Key name as symbol

Returns:

  • (Object)

59
60
61
62
63
64
65
# File 'lib/sonia/config.rb', line 59

def method_missing(sym, *args)
  if sym.to_s =~ /(.+)=$/
    self[$1] = args.first
  else
    self[sym]
  end
end

Instance Method Details

#[](key) ⇒ Object

Returns configuration value

Parameters:

  • key (#to_sym)

    Key of the value


25
26
27
# File 'lib/sonia/config.rb', line 25

def [](key)
  @data[key.to_sym]
end

#[]=(key, value) ⇒ Object

Allows setting a value

Parameters:

  • key (#to_sym)

    Key of the value

  • value (Object)

    Configuration value


33
34
35
36
37
38
39
# File 'lib/sonia/config.rb', line 33

def []=(key, value)
  if value.class == Hash
    @data[key.to_sym] = Config.new(value)
  else
    @data[key.to_sym] = value
  end
end

#each {|key, value| ... } ⇒ Object

Returns each configuration key - value pair or an iterator

Parameters:

  • (Enumerator)

Yields:

  • (key, value)

45
46
47
48
49
50
51
52
53
# File 'lib/sonia/config.rb', line 45

def each
  if block_given?
    @data.each do |k, v|
      yield k, v
    end
  else
    @data.each
  end
end

#to_hashHash

Returns whole configuration data as hash

Returns:

  • (Hash)

70
71
72
# File 'lib/sonia/config.rb', line 70

def to_hash
  @data
end

#update!(data) ⇒ Object

Updates configuration data

Parameters:

  • data (Hash)

16
17
18
19
20
# File 'lib/sonia/config.rb', line 16

def update!(data)
  data.each do |key, value|
    self[key] = value
  end
end