Class: ConfigAccessor::Config

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

Overview

:nodoc:

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(parent) ⇒ Config

Returns a new instance of Config.



5
6
7
8
9
10
11
12
13
# File 'lib/config_accessor/config.rb', line 5

def initialize(parent)
  super()

  @transformers = parent.respond_to?(:transformers) ? parent.transformers.dup : {}

  parent.each_pair do |k, v|
    self[k] = try_duplicate(v)
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missingObject

uniform access

c = Config.new
c.port 80
c.port # => 80


57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/config_accessor/config.rb', line 57

def access(key, *args, &block)
  if args.empty? && !block
    self[key]
  else
    raise ArgumentError, 'Too many arguments (%s for 1)' % args.length if args.length > 1

    val = args.first || block
    val = @transformers[key.to_sym].call(val) if @transformers[key.to_sym].respond_to?(:call)

    self[key] = val
  end
end

Instance Attribute Details

#transformersObject (readonly)

Returns the value of attribute transformers.



3
4
5
# File 'lib/config_accessor/config.rb', line 3

def transformers
  @transformers
end

Instance Method Details

#[](key) ⇒ Object

indifferent access



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

def [](key)
  super(key.to_sym)
end

#[]=(key, value) ⇒ Object

indifferent access



37
38
39
# File 'lib/config_accessor/config.rb', line 37

def []=(key, value)
  super(key.to_sym, value)
end

#access(key, *args, &block) ⇒ Object Also known as: method_missing

uniform access

c = Config.new
c.port 80
c.port # => 80


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

def access(key, *args, &block)
  if args.empty? && !block
    self[key]
  else
    raise ArgumentError, 'Too many arguments (%s for 1)' % args.length if args.length > 1

    val = args.first || block
    val = @transformers[key.to_sym].call(val) if @transformers[key.to_sym].respond_to?(:call)

    self[key] = val
  end
end

#dupObject

Make a deep copy of Config



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

def dup
  Config.new(self)
end

#fetch(key) ⇒ Object

indifferent access



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

def fetch(key)
  super(key.to_sym)
end

#register_transformer(name, proc) ⇒ Object

Raises:

  • (TypeError)


20
21
22
23
24
# File 'lib/config_accessor/config.rb', line 20

def register_transformer(name, proc)
  raise TypeError, 'transformer must be Symbol, Method or Proc' unless proc.respond_to?(:to_proc)

  @transformers[name.to_sym] = proc.to_proc
end