Skip to content

Custom Adapter for Overriding root key #1163

@sbauch

Description

@sbauch

I'm in the process of upgrading to 0.10.0.rc2. I'm a little bit inconsistent throughout the client app in terms of whether to expect a root or not, something I'll eventually get around to fixing.

But for now I need the functionality present in previous versions that allow me to pass a :root option, including nil to a serializer in order to customize or remove the root key from a json result.

So I think I want the ActiveModel::Serializer::Adapter::Json but with the ability to override the root key.

I went ahead and took a stab at implementing this, hoping someone can provide a little bit of feedback for it and let me know whether there's a more efficient way to achieve what I'm looking to do

module My
  class CustomAdapter < ActiveModel::Serializer::Adapter::Json

    def serializable_hash(options = nil)
      json = super(options)

      if options.keys.include?(:root)
        if options[:root]
          {options[:root] => json[root]}
        else
          json[root]
        end
      else
        json
      end
    end
  end
end

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions