I want to leverage AMS to create json data to pass as GraphQL variables in my test suite. Apparently, it support :camel_lower
which would convert hash keys like :some_field
to :someField
but I can't seem to get it to work. Here's the relevant code:
/config/initializers/active_model_serializers.rb:
ActiveModelSerializers.config.key_transform = :camel_lower
/app/serializers/service_serializer.rb:
class ServiceSerializer < ApplicationSerializer
attributes :id, :name, :time_increment
end
rails console:
ActiveModelSerializers.config.key_transform
=> :camel_lower
s = Service.new(name: 'Test', time_increment: 10)
=> #<Service id: nil, name: "Test", time_increment: 10, created_at: nil, updated_at: nil>
ss = ServiceSerializer.new(s)
=> #<ServiceSerializer:0x00007f3771dd9dc0 @object=#<Service id: nil, name: "Test", time_increment: 10, created_at: nil, updated_at: nil>, @instance_options={}, @root=nil, @scope=nil>
ss.as_json
=> {:id=>nil, :name=>"Test", :time_increment=>10}
The result I was expecting was:
=> {:id=>nil, :name=>"Test", :timeIncrement=>10}
ActiveModelSerializers
has been in some sort of maintainance state for a long time and doesn't seem to be receiving any updates.
My personal choice has been either the blueprinter
gem or jsonapi-serializers
. The blueprinter
one is closer to AMS.
It is very easy to work with
# Gemfile
gem 'blueprinter'
and the usual
bundle install
Creating a serializer is very straightforward
# e.g. app/blueprinter/service_blueprint.rb
class ServiceBlueprint < Blueprinter::Base
# identifier :id
fields :id, :name, :time_increment
end
Add a class LowerCamelTransformer
# e.g. app/blueprinter/lower_camel_transformer.rb
class LowerCamelTransformer < Blueprinter::Transformer
def transform(hash, _object, _options)
hash.transform_keys! { |key| key.to_s.camelize(:lower).to_sym }
end
end
And in config/initializers/blueprinter.rb
Blueprinter.configure do |config|
config.default_transformers = [LowerCamelTransformer]
end
Test it
s = Service.find(1)
puts ServiceBlueprint.render(s)
# Will give you a nice output with lower camel case