diff --git a/lib/active_model_serializers/key_transform.rb b/lib/active_model_serializers/key_transform.rb index d0e648e59..01044933c 100644 --- a/lib/active_model_serializers/key_transform.rb +++ b/lib/active_model_serializers/key_transform.rb @@ -4,6 +4,7 @@ module ActiveModelSerializers module KeyTransform module_function + SLASH_SYMBOL = '/'.freeze # Transforms values to UpperCamelCase or PascalCase. # # @example: @@ -14,7 +15,7 @@ def camel(value) when Array then value.map { |item| camel(item) } when Hash then value.deep_transform_keys! { |key| camel(key) } when Symbol then camel(value.to_s).to_sym - when String then value.underscore.camelize + when String then camelize(value, :upper) else value end end @@ -29,7 +30,7 @@ def camel_lower(value) when Array then value.map { |item| camel_lower(item) } when Hash then value.deep_transform_keys! { |key| camel_lower(key) } when Symbol then camel_lower(value.to_s).to_sym - when String then value.underscore.camelize(:lower) + when String then camelize(value, :lower) else value end end @@ -70,5 +71,9 @@ def underscore(value) def unaltered(value) value end + + def camelize(value, first_letter) + value.split(SLASH_SYMBOL).map { |ch| ch.underscore.camelize(first_letter) }.join(SLASH_SYMBOL) + end end end diff --git a/test/active_model_serializers/key_transform_test.rb b/test/active_model_serializers/key_transform_test.rb index b4ff4d311..fbb02d6f8 100644 --- a/test/active_model_serializers/key_transform_test.rb +++ b/test/active_model_serializers/key_transform_test.rb @@ -68,6 +68,10 @@ def test_camel expected: [ { SomeValue: 'value' } ] + }, + { + value: 'scope/some_value', + expected: 'Scope/SomeValue' } ] scenarios.each do |s| @@ -142,6 +146,10 @@ def test_camel_lower expected: [ { someValue: 'value' } ] + }, + { + value: 'scope/some_value', + expected: 'scope/someValue' } ] scenarios.each do |s|