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
# File 'lib/usable/config.rb', line 11

def initialize
  @spec = OpenStruct.new
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



44
45
46
47
48
49
50
51
52
# File 'lib/usable/config.rb', line 44

def method_missing(method_name, *args, &block)
  if block
    _spec.define_singleton_method(method_name) { yield }
  else
    spec method_name, *args
  end
rescue => e
  super
end

Instance Method Details

#[](key) ⇒ Object



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

def [](key)
  spec key
end

#[]=(key, val) ⇒ Object



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

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

#_specObject



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

def _spec
  @spec
end

#call_lazy_method(key) ⇒ Object



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

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

#each(&block) ⇒ Object



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

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

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

Returns:

  • (Boolean)


54
55
56
# File 'lib/usable/config.rb', line 54

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



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

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