Module: A2A::Extensions::CaseTransformation
- Defined in:
- lib/a2a/extensions/case_transformation.rb
Overview
Allows a dry-struct to be instantiated and serialized with camelCase keys.
Class Method Summary collapse
Instance Method Summary collapse
-
#camelize(value) ⇒ Object
Converts hash keys from snake_case to camelCase recursively.
-
#to_json(camel_case: true) ⇒ String
Serializes the object to JSON with an option for camelCase formatting.
Class Method Details
.included(base) ⇒ Object
7 8 9 10 11 12 |
# File 'lib/a2a/extensions/case_transformation.rb', line 7 def self.included(base) base.class_eval do # Transform keys to snake_case symbols when initializing the struct transform_keys { |key| INFLECTOR.underscore(key.to_s).to_sym } end end |
Instance Method Details
#camelize(value) ⇒ Object
Converts hash keys from snake_case to camelCase recursively
20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/a2a/extensions/case_transformation.rb', line 20 def camelize(value) case value when Array value.map { |item| camelize(item) } when Hash value.to_h do |key, v| [INFLECTOR.camelize_lower(key.to_s).to_sym, camelize(v)] end else value end end |
#to_json(camel_case: true) ⇒ String
Serializes the object to JSON with an option for camelCase formatting
39 40 41 42 43 |
# File 'lib/a2a/extensions/case_transformation.rb', line 39 def to_json(camel_case: true, **) data = to_h data = camelize(data) if camel_case data.to_json(**) end |