[BAC-381] Enhance from_json with metamagic - #19
Conversation
There was a problem hiding this comment.
Pull Request Overview
This PR enhances JSON parsing functionality by adding support for camelCase attribute aliases. The implementation allows entities to automatically handle JSON keys in camelCase format by creating aliases for snake_case attributes.
- Introduces a new
CamelCaseablemodule that automatically creates camelCase aliases for attributes - Updates JSON parser to use attribute aliases when setting values from JSON
- Modifies the parsing logic to iterate over camelized attribute names instead of original attribute names
Reviewed Changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
lib/active_model/entity.rb |
Includes the new CamelCaseable module in the Entity base class |
lib/active_model/entity/camel_caseable.rb |
New module that creates camelCase aliases for attributes and tracks camelized names |
lib/active_model/entity/parsers/json.rb |
Updates JSON parsing to resolve attribute aliases and use camelized attribute names |
Comments suppressed due to low confidence (1)
lib/active_model/entity/camel_caseable.rb:17
- The variable name 'camelize_name' is grammatically incorrect. It should be 'camelized_name' to properly indicate that it's the camelized version of the name.
camelize_name = name.to_s.camelize(:lower)
|
|
||
| return unless name.to_s != camelize_name | ||
|
|
||
| alias_attribute camelize_name.to_sym, name |
There was a problem hiding this comment.
The indentation is inconsistent here. This line appears to be over-indented compared to the surrounding code block.
| alias_attribute camelize_name.to_sym, name | |
| alias_attribute camelize_name.to_sym, name |
| next unless unified_json.key?(name) | ||
|
|
||
| instance.set_attribute_from_json(name, unified_json[field_name]) | ||
| instance.set_attribute_from_json(name, unified_json[name]) |
There was a problem hiding this comment.
This logic skips processing when the JSON key is not present, but the original code would still call 'set_attribute_from_json' even with nil values. This change in behavior could cause attributes to not be initialized properly if they expect to handle nil values.
Approx x2 perf
tested with:
words-big.json