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
Also known as:
marshal_load
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
# File 'lib/usable/config.rb', line 46
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
75
76
77
78
79
|
# File 'lib/usable/config.rb', line 75
def freeze
to_h.each { |key, value| define_singleton_method(key) { value } }
@spec.freeze
super
end
|
#inspect ⇒ Object
Also known as:
to_s
81
82
83
84
85
86
87
88
|
# File 'lib/usable/config.rb', line 81
def inspect
nested, locals = @spec.to_h.partition { |_, value| value.is_a?(Usable::Config) }
nested.map! { |key, _| [key, '{...}'] }
locals.concat nested
locals.map! { |key, v| %(@#{key}=#{v.inspect}) }
vars = locals.any? ? ' ' + locals.join(', ') : ''
"<Usable::Config:0x00#{(object_id << 1).to_s(16)}#{vars}>"
end
|
#merge(other) ⇒ Object
42
43
44
|
# File 'lib/usable/config.rb', line 42
def merge(other)
to_h.merge(other)
end
|
#respond_to_missing?(method_name, _private = false) ⇒ Boolean
71
72
73
|
# File 'lib/usable/config.rb', line 71
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
|