Class: Usable::Config
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
#+
#add_module, #available_methods, #modules
Constructor Details
#initialize(attributes = {}) ⇒ Config
TODO:
Maybe keep a list of all attributes (lazy and regular)? e.g @attributes = Set.new attributes.keys.map(&:to_s)
Returns a new instance of Config.
12
13
14
15
|
# File 'lib/usable/config.rb', line 12
def initialize(attributes = {})
@spec = OpenStruct.new(attributes)
@lazy_loads = Set.new
end
|
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(key, *args, &block) ⇒ Object
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
# File 'lib/usable/config.rb', line 45
def method_missing(key, *args, &block)
if block
@lazy_loads << key
@spec.define_singleton_method(key) { yield }
else
key = key.to_s.tr('=', '').to_sym
if args.empty?
if @spec[key]
@lazy_loads.delete key
else
@spec[key] = call_spec_method(key)
end
define_singleton_method(key) { @spec[key] }
@spec[key]
else
@spec[key] = args.first
end
end
rescue NoMethodError
super
end
|
Instance Method Details
#[](key) ⇒ Object
21
22
23
|
# File 'lib/usable/config.rb', line 21
def [](key)
@spec[key]
end
|
#[]=(key, val) ⇒ Object
25
26
27
|
# File 'lib/usable/config.rb', line 25
def []=(key, val)
@spec[key] = val
end
|
#each(&block) ⇒ Object
29
30
31
|
# File 'lib/usable/config.rb', line 29
def each(&block)
@spec.to_h.each(&block)
end
|
#freeze ⇒ Object
74
75
76
77
78
|
# File 'lib/usable/config.rb', line 74
def freeze
to_h.each { |key, value| define_singleton_method(key) { value } }
@spec.freeze
super
end
|
#marshal_load(attributes = {}) ⇒ Object
80
81
82
|
# File 'lib/usable/config.rb', line 80
def marshal_load(attributes = {})
initialize(attributes)
end
|
#merge(other) ⇒ Object
41
42
43
|
# File 'lib/usable/config.rb', line 41
def merge(other)
to_h.merge(other)
end
|
#respond_to_missing?(method_name, _private = false) ⇒ Boolean
70
71
72
|
# File 'lib/usable/config.rb', line 70
def respond_to_missing?(method_name, _private = false)
method_name.to_s.end_with?('=') || @spec.respond_to?(method_name)
end
|
#spec ⇒ Object
17
18
19
|
# File 'lib/usable/config.rb', line 17
def spec
@spec
end
|
#to_h ⇒ Object
Also known as:
to_hash, marshal_dump
33
34
35
36
|
# File 'lib/usable/config.rb', line 33
def to_h
@lazy_loads.each { |key| @spec[key] = call_spec_method(key) }
@spec.to_h
end
|