Class: Usable::Config

Inherits:
Object
  • Object
show all
Includes:
ConfigMulti, ConfigRegister
Defined in:
lib/usable/config.rb

Overview

Store and manage configuration settings. Keep methods to a minimum since this class relies on method_missing to read and write to the underlying @spec object

Instance Method Summary collapse

Methods included from ConfigMulti

#+

Methods included from ConfigRegister

#add_module, #available_methods, #modules

Constructor Details

#initializeConfig

Returns a new instance of Config.



11
12
13
14
# File 'lib/usable/config.rb', line 11

def initialize
  @spec = OpenStruct.new
  @lazy_loads = Set.new
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



53
54
55
56
57
58
59
60
61
62
# File 'lib/usable/config.rb', line 53

def method_missing(method_name, *args, &block)
  if block
    _spec.define_singleton_method(method_name) { yield }
    @lazy_loads << method_name
  else
    spec method_name, *args
  end
rescue NoMethodError
  super
end

Instance Method Details

#[](key) ⇒ Object



33
34
35
# File 'lib/usable/config.rb', line 33

def [](key)
  spec key
end

#[]=(key, val) ⇒ Object



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

def []=(key, val)
  spec key, val
end

#_specObject



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

def _spec
  @spec
end

#call_lazy_method(key) ⇒ Object



48
49
50
51
# File 'lib/usable/config.rb', line 48

def call_lazy_method(key)
  @lazy_loads.delete key
  @spec.public_send key.to_s.tr('=', '')
end

#each(&block) ⇒ Object



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

def each(&block)
  @spec.to_h.each(&block)
end

#respond_to_missing?(method_name, _private = false) ⇒ Boolean

Returns:

  • (Boolean)


64
65
66
# File 'lib/usable/config.rb', line 64

def respond_to_missing?(method_name, _private = false)
  method_name.to_s.end_with?('=') || _spec.respond_to?(method_name)
end

#spec(key, value = nil) ⇒ Object



20
21
22
23
24
25
26
27
# File 'lib/usable/config.rb', line 20

def spec(key, value = nil)
  if value
    @spec[key.to_s.tr('=', '')] = value
  else
    # Handle the case where the value may be defined with a block, in which case it's a method
    @spec[key] ||= call_lazy_method(key)
  end
end

#to_hObject Also known as: to_hash



41
42
43
44
# File 'lib/usable/config.rb', line 41

def to_h
  @lazy_loads.each { |key| spec(key) }
  _spec.to_h
end