|
| 1 | +# frozen_string_literal: true |
| 2 | +require 'active_support/core_ext/hash/keys' |
| 3 | +require 'active_support/core_ext/string' |
| 4 | + |
| 5 | +require 'json_key_transform/version' |
| 6 | + |
| 7 | +module JsonKeyTransform |
| 8 | + module_function |
| 9 | + |
| 10 | + # Transforms values to UpperCamelCase or PascalCase. |
| 11 | + # |
| 12 | + # @example: |
| 13 | + # "some_key" => "SomeKey", |
| 14 | + def camel(value) |
| 15 | + case value |
| 16 | + when Array then value.map { |item| camel(item) } |
| 17 | + when Hash then value.deep_transform_keys! { |key| camel(key) } |
| 18 | + when Symbol then camel(value.to_s).to_sym |
| 19 | + when String then value.underscore.camelize |
| 20 | + else value |
| 21 | + end |
| 22 | + end |
| 23 | + |
| 24 | + # Transforms values to camelCase. |
| 25 | + # |
| 26 | + # @example: |
| 27 | + # "some_key" => "someKey", |
| 28 | + def camel_lower(value) |
| 29 | + case value |
| 30 | + when Array then value.map { |item| camel_lower(item) } |
| 31 | + when Hash then value.deep_transform_keys! { |key| camel_lower(key) } |
| 32 | + when Symbol then camel_lower(value.to_s).to_sym |
| 33 | + when String then value.underscore.camelize(:lower) |
| 34 | + else value |
| 35 | + end |
| 36 | + end |
| 37 | + |
| 38 | + # Transforms values to dashed-case. |
| 39 | + # This is the default case for the JsonApi adapter. |
| 40 | + # |
| 41 | + # @example: |
| 42 | + # "some_key" => "some-key", |
| 43 | + def dash(value) |
| 44 | + case value |
| 45 | + when Array then value.map { |item| dash(item) } |
| 46 | + when Hash then value.deep_transform_keys! { |key| dash(key) } |
| 47 | + when Symbol then dash(value.to_s).to_sym |
| 48 | + when String then value.underscore.dasherize |
| 49 | + else value |
| 50 | + end |
| 51 | + end |
| 52 | + |
| 53 | + # Transforms values to underscore_case. |
| 54 | + # This is the default case for deserialization in the JsonApi adapter. |
| 55 | + # |
| 56 | + # @example: |
| 57 | + # "some-key" => "some_key", |
| 58 | + def underscore(value) |
| 59 | + case value |
| 60 | + when Array then value.map { |item| underscore(item) } |
| 61 | + when Hash then value.deep_transform_keys! { |key| underscore(key) } |
| 62 | + when Symbol then underscore(value.to_s).to_sym |
| 63 | + when String then value.underscore |
| 64 | + else value |
| 65 | + end |
| 66 | + end |
| 67 | + |
| 68 | + # Returns the value unaltered |
| 69 | + def unaltered(value) |
| 70 | + value |
| 71 | + end |
| 72 | +end |
0 commit comments