Class: CamelSnakeStruct
- Inherits:
-
Object
show all
- Defined in:
- lib/camel_snake_struct.rb
Class Method Summary
collapse
Instance Method Summary
collapse
Constructor Details
Returns a new instance of CamelSnakeStruct.
21
22
23
24
25
26
27
28
|
# File 'lib/camel_snake_struct.rb', line 21
def initialize(hash)
@_raw_hash = hash&.to_h || {}
@_method_to_key = @_raw_hash.keys.each_with_object({}) do |key, mapping|
normalize_key = key.gsub('@', '').gsub('.', '_')
mapping[normalize_key] = key
mapping[normalize_key.underscore] = key
end
end
|
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method_name, *arguments, &block) ⇒ Object
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
# File 'lib/camel_snake_struct.rb', line 56
def method_missing(method_name, *arguments, &block)
camelize_key = __method_to_key(method_name)
if camelize_key
if _define_new_method(method_name, camelize_key)
send(method_name)
else @_raw_hash[camelize_key]
end
elsif method_name.to_s.end_with?('?')
camelize_key = __method_to_key(method_name.to_s.chop)
@_raw_hash.key?(camelize_key)
else
super
end
end
|
Class Method Details
.example(data) ⇒ Object
5
6
7
8
|
# File 'lib/camel_snake_struct.rb', line 5
def self.example(data)
new_example = new(data)
walk_example(new_example)
end
|
.walk_example(new_example) ⇒ Object
10
11
12
13
14
15
16
17
18
19
|
# File 'lib/camel_snake_struct.rb', line 10
def self.walk_example(new_example)
new_example.send(:_method_to_key).keys.each do |m_name|
result = new_example.public_send(m_name)
if result.is_a?(CamelSnakeStruct)
walk_example(result)
elsif result.is_a?(Array) && result.first.is_a?(CamelSnakeStruct)
walk_example(result.first)
end
end
end
|
Instance Method Details
#[](key) ⇒ Object
30
31
32
|
# File 'lib/camel_snake_struct.rb', line 30
def [](key)
_val(@_raw_hash[key])
end
|
#to_h ⇒ Object
34
35
36
|
# File 'lib/camel_snake_struct.rb', line 34
def to_h
to_hash
end
|
#to_hash ⇒ Object
38
39
40
|
# File 'lib/camel_snake_struct.rb', line 38
def to_hash
@_raw_hash
end
|