Class: Bonfig::BlankConfig

Inherits:
BasicObject
Defined in:
lib/bonfig.rb

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ BlankConfig

Returns a new instance of BlankConfig.



3
4
5
6
# File 'lib/bonfig.rb', line 3

def initialize(&block)
  @_data = ::Hash.new
  instance_eval(&block)
end

Instance Method Details

#[](key) ⇒ Object



21
22
23
# File 'lib/bonfig.rb', line 21

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

#_nested(name, &block) ⇒ Object (protected)



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/bonfig.rb', line 42

def _nested(name, &block)
  nested = @_data[name] = BlankConfig.new(&block)

  define_method(name) do |&b|
    if b
      b.call(nested)
    else
      @_data[name]
    end
  end

  define_method("#{name}=") do |val|
    if val.is_a?(::Hash)
      nested._update(val)
    else
      fail 'Can\'t assign value to nested config.'
    end
  end
end

#_update(data) ⇒ Object (protected)



38
39
40
# File 'lib/bonfig.rb', line 38

def _update(data)
  @_data.update(data)
end

#config(name, options = {}, &block) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/bonfig.rb', line 8

def config(name, options = {}, &block)
  name = name.to_sym
  if block
    _nested(name, &block)
  else
    @_data[name] = options[:default]
    define_method("#{name}=") { |value| @_data[name] = value }
    define_method(name) { @_data[name] }
  end

  define_method("#{name}?") { @_data.key?(name) }
end

#define_method(name, &block) ⇒ Object (protected)



62
63
64
65
66
67
# File 'lib/bonfig.rb', line 62

def define_method(name, &block)
  name = name.to_sym
  (class << self; self; end).class_eval do
    define_method(name, &block)
  end
end

#instance_of?(klass) ⇒ Boolean

Returns:

  • (Boolean)


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

def instance_of?(klass)
  klass == BlankConfig
end

#to_hashObject



25
26
27
28
29
30
# File 'lib/bonfig.rb', line 25

def to_hash
  @_data.reduce({}) do |accum, (k, val)|
    accum[k] = val.instance_of?(BlankConfig) ? val.to_hash : val
    accum
  end
end