Class: Settings

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

Overview

Based on: mjijackson.com/2010/02/flexible-ruby-config-objects Authors: Michael Jackson, Haydn Ewers

Instance Method Summary collapse

Constructor Details

#initialize(data = {}) ⇒ Settings

Returns a new instance of Settings.



5
6
7
8
# File 'lib/settings.rb', line 5

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



36
37
38
39
40
41
42
# File 'lib/settings.rb', line 36

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

Instance Method Details

#[](key) ⇒ Object



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

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

#[]=(key, value) ⇒ Object



20
21
22
23
24
25
26
# File 'lib/settings.rb', line 20

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

#to_hashObject



28
29
30
# File 'lib/settings.rb', line 28

def to_hash
  @data.to_hash
end

#to_sObject



32
33
34
# File 'lib/settings.rb', line 32

def to_s
  @data.to_s
end

#update!(data) ⇒ Object



10
11
12
13
14
# File 'lib/settings.rb', line 10

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