Module: Async::Matrix::ApplicationService::Config::Vivify

Defined in:
lib/async/matrix/application_service/config/vivify.rb

Overview

Mixin that gives a Hash dot-notation accessors with autovivification.

Not applied globally — only extended onto the validated config hash and its nested children so the rest of the world is unaffected.

h = {}.extend(Vivify)
h.foo.bar.baz = 42
h  # => { foo: { bar: { baz: 42 } } }

Class Method Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/async/matrix/application_service/config/vivify.rb', line 20

def method_missing(name, *args)
  key = name.to_s

  if key.end_with?("=")
    self[key.chomp("=").to_sym] = args.first
  elsif key?(name.to_sym)
    self[name.to_sym]
  elsif key.start_with?("to_")
    super
  else
    self[name.to_sym] = {}.extend(Vivify)
  end
end

Class Method Details

.deep_vivify(obj) ⇒ Object

Recursively symbolize keys and extend every nested Hash with Vivify.

Call this on the raw (string-keyed) hash that comes out of YAML.safe_load / JSON Schema validation before wrapping it in Config.



42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/async/matrix/application_service/config/vivify.rb', line 42

def self.deep_vivify(obj)
  case obj
  when Hash
    result = {}
    obj.each { |k, v| result[k.to_s.to_sym] = deep_vivify(v) }
    result.extend(Vivify)
  when Array
    obj.map { |v| deep_vivify(v) }
  else
    obj
  end
end

Instance Method Details

#respond_to_missing?(name, _priv = false) ⇒ Boolean

Returns:

  • (Boolean)


34
35
36
# File 'lib/async/matrix/application_service/config/vivify.rb', line 34

def respond_to_missing?(name, _priv = false)
  name.to_s.end_with?("=") || key?(name.to_sym) || super
end