Class: Ribbon::Config

Inherits:
Object
  • Object
show all
Defined in:
lib/ribbon/config.rb,
lib/ribbon/config/version.rb

Defined Under Namespace

Classes: ConfigError, NotAddableError, ProcArray, UndefinedValue

Constant Summary collapse

VERSION =
"0.1.0"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name = nil, &block) ⇒ Config

Returns a new instance of Config.



31
32
33
34
# File 'lib/ribbon/config.rb', line 31

def initialize(name=nil, &block)
  @name = name
  define(&block) if block_given?
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(meth, *args, &block) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/ribbon/config.rb', line 61

def method_missing(meth, *args, &block)
  meth_str = meth.to_s

  if /^(\w+)\=$/.match(meth_str)
    _set($1, *args, &block)
  elsif args.length > 0 || block_given?
    _add(meth, *args, &block)
  elsif /^(\w+)\?$/.match(meth_str)
    !!_get($1)
  else
    _get_or_create_namespace(meth)
  end
end

Instance Attribute Details

#name ⇒ Object (readonly)

Returns the value of attribute name.



29
30
31
# File 'lib/ribbon/config.rb', line 29

def name
  @name
end

Instance Method Details

#define(&block) ⇒ Object



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

def define(&block)
  case block.arity
  when 0 then instance_eval(&block)
  when 1 then block.call(self)
  else   raise ConfigError, 'invalid config block arity'
  end
end

#dup ⇒ Object

Deep dup all the values.



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/ribbon/config.rb', line 45

def dup
  super.tap do |new_config|
    new_config.instance_variable_set(
      :@_nested,
      Hash[
        _nested.map { |key, object|
          [
            key,
            object.is_a?(Config) ? object.dup : object
          ]
        }
      ]
    )
  end
end

#merge_config_file!(file) ⇒ Object



87
88
89
# File 'lib/ribbon/config.rb', line 87

def merge_config_file!(file)
  merge_hash!(YAML.load_file(file))
end

#merge_hash!(hash) ⇒ Object



75
76
77
78
79
80
81
82
83
84
85
# File 'lib/ribbon/config.rb', line 75

def merge_hash!(hash)
  hash.each { |k, v|
    if v.is_a?(Hash)
      send(k).merge_hash!(v)
    else
      send("#{k}=", v)
    end
  }

  self
end