Class: EasySettings::Struct
- Inherits:
-
Object
- Object
- EasySettings::Struct
show all
- Includes:
- Enumerable
- Defined in:
- lib/easy-settings/struct.rb
Constant Summary
collapse
- UnknownPropertyError =
Class.new(StandardError)
Class Method Summary
collapse
Instance Method Summary
collapse
Constructor Details
#initialize(properties = {}) ⇒ Struct
Returns a new instance of Struct.
22
23
24
|
# File 'lib/easy-settings/struct.rb', line 22
def initialize(properties = {})
@properties = properties
end
|
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method, *args) ⇒ Object
46
47
48
49
50
51
52
53
|
# File 'lib/easy-settings/struct.rb', line 46
def method_missing(method, *args)
method = method.to_s
return @properties.fetch(method) unless method.end_with?("=")
property = method[0..-2]
@properties[property] = args[0]
rescue KeyError => e
raise_unknown_property(method)
end
|
Class Method Details
.import(hash) ⇒ Object
8
9
10
11
12
13
14
15
16
17
18
19
20
|
# File 'lib/easy-settings/struct.rb', line 8
def self.import(hash)
new.tap do |struct|
hash.each do |k, v|
case v
when Hash
v = import(v)
when Array
v = v.collect{ |i| i.is_a?(Hash) ? import(i) : i }
end
struct[k] = v
end
end
end
|
Instance Method Details
#[](property) ⇒ Object
26
27
28
|
# File 'lib/easy-settings/struct.rb', line 26
def [](property)
@properties.fetch(property.to_s){ raise_unknown_property(property) }
end
|
#[]=(property, value) ⇒ Object
30
31
32
|
# File 'lib/easy-settings/struct.rb', line 30
def []=(property, value)
@properties[property.to_s] = value
end
|
#raise_unknown_property(property) ⇒ Object
55
56
57
|
# File 'lib/easy-settings/struct.rb', line 55
def raise_unknown_property(property)
raise UnknownPropertyError, "unknown property #{property.inspect} (#{@properties.keys.map(&:inspect).join(", ")})"
end
|
#respond_to?(property, include_private = false) ⇒ Boolean
42
43
44
|
# File 'lib/easy-settings/struct.rb', line 42
def respond_to?(property, include_private = false)
@properties.has_key?(property.to_s)
end
|
#to_h ⇒ Object
38
39
40
|
# File 'lib/easy-settings/struct.rb', line 38
def to_h
@properties.transform_values{ |v| v.is_a?(EasySettings::Struct) ? v.to_h : v }
end
|
#try(property) ⇒ Object
34
35
36
|
# File 'lib/easy-settings/struct.rb', line 34
def try(property)
@properties[property.to_s]
end
|