Class: Announcer::Config

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

Defined Under Namespace

Classes: ConfigError, NotAddableError, ProcArray, UndefinedValue

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Config.



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

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



59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/announcer/config.rb', line 59

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

#nameObject (readonly)

Returns the value of attribute name.



27
28
29
# File 'lib/announcer/config.rb', line 27

def name
  @name
end

Instance Method Details

#define(&block) ⇒ Object



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

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

#dupObject

Deep dup all the values.



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/announcer/config.rb', line 43

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



85
86
87
# File 'lib/announcer/config.rb', line 85

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

#merge_hash!(hash) ⇒ Object



73
74
75
76
77
78
79
80
81
82
83
# File 'lib/announcer/config.rb', line 73

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