Class: DeepStruct::HashWrapper
Instance Method Summary
collapse
Methods inherited from DeepWrapper
#initialize, #inspect, #to_json, #unwrap
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method, *args, &block) ⇒ Object
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
|
# File 'lib/deepstruct.rb', line 65
def method_missing(method, *args, &block)
return @value.send(method, *args, &block) if @value.respond_to?(method)
method = method.to_s
if method.chomp!('?')
key = method.to_sym
self.has_key?(key) && !!self[key]
elsif method.chomp!('=')
raise ArgumentError, "wrong number of arguments (#{arg_count} for 1)", caller(1) if args.length != 1
self[method] = args[0]
elsif args.length == 0 && self.has_key?(method)
self[method]
else
raise NoMethodError, "undefined method `#{method}' for #{self}", caller(1)
end
end
|
Instance Method Details
#[](key) ⇒ Object
57
58
59
|
# File 'lib/deepstruct.rb', line 57
def [](key)
indifferently(key) { |key| DeepStruct.wrap(@value[key]) }
end
|
#[]=(key, value) ⇒ Object
53
54
55
|
# File 'lib/deepstruct.rb', line 53
def []=(key, value)
indifferently(key) { |key| @value[key] = value }
end
|
#has_key?(key) ⇒ Boolean
61
62
63
|
# File 'lib/deepstruct.rb', line 61
def has_key?(key)
indifferently(key) { |key| @value.has_key?(key) }
end
|
#indifferently(key, &block) ⇒ Object
Also known as:
indiffrently
Given a symbol or a string this yields the variant of the key that exists in the wrapped hash if any. If none exists (or the key is not a symbol or string) the input value is passed through unscathed.
45
46
47
48
49
50
|
# File 'lib/deepstruct.rb', line 45
def indifferently(key, &block)
return yield(key) if @value.has_key?(key)
return yield(key.to_s) if key.is_a?(Symbol) && @value.has_key?(key.to_s)
return yield(key.to_sym) if key.is_a?(String) && @value.has_key?(key.to_sym)
return yield(key)
end
|
#respond_to?(name, include_private = false) ⇒ Boolean
31
32
33
34
35
36
37
38
39
40
|
# File 'lib/deepstruct.rb', line 31
def respond_to?(name, include_private = false)
super || @value.respond_to?(name, include_private) || case name.to_s
when /\A(.*)\?\z/
has_key?($1)
when /\=\z/
true
else
has_key?(name.to_s)
end
end
|