Guides > Adapters

Adapters

ActiveModelSerializers offers the ability to configure which adapter to use both globally and/or when when rendering. Please see Global Configurations for setting the global adapter.

The local adapter option is in the format adapter: adapter, where adapter is any of the same values as set globally.

The configured adapter can be set as a symbol, class, or class name, as described in Advanced adapter configuration.

The Attributes adapter does not include a root key. It is just the serialized attributes.

Use either the JSON or JSON API adapters if you want the response document to have a root key.

Attributes Adapter (Default)

JSON Adapter

JSON API Adapter

Advanced adapter configuration

Registering an adapter

The default adapter can be configured, as above, to use any class given to it.

An adapter may also be specified, e.g. when rendering, as a class or as a symbol. If a symbol, then the adapter must be, e.g. :great_example, ActiveModelSerializers::Adapter::GreatExample, or registered.

There are two ways to register an adapter:

1) The simplest, is to subclass ActiveModelSerializers::Adapter::Base, e.g. the below will register the Example::UsefulAdapter as "example/useful_adapter".

module Example
  class UsefulAdapter < ActiveModelSerializers::Adapter::Base
  end
end

You'll notice that the name it registers is the underscored namespace and class.

Under the covers, when the ActiveModelSerializers::Adapter::Base is subclassed, it registers the subclass as register("example/useful_adapter", Example::UsefulAdapter)

2) Any class can be registered as an adapter by calling register directly on the ActiveModelSerializers::Adapter class. e.g., the below registers MyAdapter as :special_adapter.

class MyAdapter; end
ActiveModelSerializers::Adapter.register(:special_adapter, MyAdapter)

Looking up an adapter

Method Return value
ActiveModelSerializers::Adapter.adapter_map A Hash of all known adapters { adapter_name => adapter_class }
ActiveModelSerializers::Adapter.adapters A (sorted) Array of all known adapter_names
ActiveModelSerializers::Adapter.lookup(name_or_klass) The adapter_class, else raises an ActiveModelSerializers::Adapter::UnknownAdapter error
ActiveModelSerializers::Adapter.adapter_class(adapter) Delegates to ActiveModelSerializers::Adapter.lookup(adapter)
ActiveModelSerializers::Adapter.configured_adapter A convenience method for ActiveModelSerializers::Adapter.lookup(config.adapter)

The registered adapter name is always a String, but may be looked up as a Symbol or String. Helpfully, the Symbol or String is underscored, so that get(:my_adapter) and get("MyAdapter") may both be used.

Adapter Class on GitHub

results matching ""

    No results matching ""