#409 ACTIVE MODEL SERIALIZERS

Build Status
*
*
Code Quality
*
*
*
Issue StatsPulse

About

ActiveModelSerializers brings convention over configuration to your JSON generation.

Bạn đang xem: #409 active model serializers

ActiveModelSerializers works through two components: serializersadapters.

Serializers describe which attributes & relationships should be serialized.

Adapters describe how attributes & relationships should be serialized.

SerializableResource co-ordinates the resource, Adapter & Serializer to lớn produce theresource serialization. The serialization has the #as_json, #to_json and #serializable_hashmethods used by the Rails JSON Renderer. (SerializableResource actually delegatesthese methods to the adapter.)

By default ActiveModelSerializers will use the Attributes Adapter (no JSON root).But we strongly advise you lớn use JsonApi Adapter, whichfollows 1.0 of the format specified in jsonapi.org/format.Check how to change the adapter in the sections below.

0.10.x is not backward compatible with 0.9.x nor 0.8.x.

0.10.x is based on the 0.8.0 code, but with a more flexiblearchitecture. We'd love your help. Learn how you can help here.

Installation

Add this line to lớn your application's Gemfile:

gem 'active_model_serializers', '~> 0.10.0'And then execute:

$ bundle

Getting Started

See Getting Started for the nuts & bolts.

More information is available in the Guides andHigh-cấp độ behavior.

Getting Help

If you find a bug, please report an Issue& see our contributing guide.

If you have a question, please post khổng lồ Staông xã Overflow.

If you'd like lớn chat, we have sầu a community slachồng.

Thanks!

Documentation

If you're reading this at https://github.com/rails-api/active_model_serializers you arereading documentation for our master, which may include features that have sầu notbeen released yet. Please see below for the documentation relevant lớn you.

0.10.10 (lathử nghiệm release) Documentation0.9 (0-9-stable) Documentation0.8 (0-8-stable) Documentation

High-màn chơi behavior

Choose an adapter from adapters:

ActiveModelSerializers.config.adapter = :json_api # Default: `:attributes`Given a serializable model:

# eitherclass SomeResource ActiveRecord::Base # columns: title, bodyend# orclass SomeResource ActiveModelSerializers::Model attributes :title, :bodyendAnd initialized as:

resource = SomeResource.new(title: 'ActiveModelSerializers', body: 'Convention over configuration')Given a serializer for the serializable model:

class SomeSerializer ActiveModel::Serializer attribute :title, key: :name attributes :bodyendThe mã sản phẩm can be serialized as:

options = serialization = ActiveModelSerializers::SerializableResource.new(resource, options)serialization.to_jsonserialization.as_jsonSerializableResource delegates to lớn the adapter, which it builds as:

adapter_options = adapter = ActiveModelSerializers::Adapter.create(serializer, adapter_options)adapter.to_jsonadapter.as_jsonadapter.serializable_hashThe adapter formats the serializer's attributes và associations (a.k.a. includes):

serializer_options = serializer = SomeSerializer.new(resource, serializer_options)serializer.attributesserializer.associations

Architecture

This section focuses on architecture the 0.10.x version of ActiveModelSerializers. If you are interested in the architecture of the 0.8 or 0.9 versions,please refer to lớn the 0.8 README or0.9 README.

Xem thêm: Jual Eisen Vitamin C Là Gì, Viãªn SủIâ Mivolis Eisen Vitamin C 20 Viãªnâ

The original thiết kế is also available here.

ActiveModel::Serializer

An ActiveModel::Serializer wraps a serializable resourceand exposes an attributes method, among mỏi a few others.It allows you to lớn specify which attributes & associations should be represented in the serializatation of the resource.It requires an adapter to transform its attributes into a JSON document; it cannot be serialized itself.It may be useful lớn think of it as apresenter.

ActiveModel::CollectionSerializer

The ActiveModel::CollectionSerializer represents a collection of resources as serializers&, if there is no serializer, primitives.

ActiveModelSerializers::Adapter::Base

The ActiveModelSerializers::Adapter::Base describes the structure of the JSON document generated from aserializer. For example, the Attributes example represents each serializer as itsunmodified attributes. The JsonApi adapter represents the serializer as a JSONAPI document.

ActiveModelSerializers::SerializableResource

The ActiveModelSerializers::SerializableResource acts to lớn coordinate the serializer(s) & adapterto an object that responds to to_json, and as_json. It is used in the controller toencapsulate the serialization resource when rendered. However, it can also be used on its ownto serialize a resource outside of a controller, as well.

Primitive sầu handling

Definitions: A primitive is usually a String or Array. There is no serializerdefined for them; they will be serialized when the resource is converted khổng lồ JSON (as_json orto_json). (The below also applies for any object with no serializer.)

ActiveModelSerializers doesn't handle primitives passed khổng lồ render json: at all.

Internally, if no serializer can be found in the controller, the resource is not decorated byActiveModelSerializers.

However, when a primitive sầu value is an attribute or in a collection, it is not modified.

When serializing a collection & the collection serializer (CollectionSerializer) cannotidentify a serializer for a resource in its collection, it throws :no_serializer.For example, when caught by Reflection#build_association, & the association value is phối directly:

reflection_options<:virtual_value> = association_value.try(:as_json) || association_value(which is called by the adapter as serializer.associations(*).)

How options are parsed

High-màn chơi overview:

For a collection:serializer specifies the collection serializer and:each_serializer specifies the serializer for each resource in the collection.For a single resource, the :serializer option is the resource serializer.

Details:

ActionController::Serializationserializable_resource = ActiveModelSerializers::SerializableResource.new(resource, options)ActiveModelSerializers::SerializableResourceif serializable_resource.serializer? (there is a serializer for the resource, và an adapter is used.)Where serializer? is use_adapter? && !!(serializer)Where use_adapter?: 'True when no explicit adapter given, or explicit value is truthy (non-nil);False when explicit adapter is falsy (nil or false)'Where serializer:from explicit :serializer option, elseimplicitly from resource ActiveModel::Serializer.serializer_for(resource)A side-effect of checking serializer is:The :serializer option is removed from the serializer_opts hashIf the :each_serializer option is present, it is removed from the serializer_opts hash and mix as the :serializer optionThe serializer & adapter are created asserializer_instance = serializer.new(resource, serializer_opts)adapter_instance = ActiveModel::Serializer::Adapter.create(serializer_instance, adapter_opts)ActiveModel::Serializer::CollectionSerializer#newActiveModel::Serializer#attributes is used by the adapter lớn get the attributes forresource as defined by the serializer.

(In Rails, the options are also passed khổng lồ the as_json(options) or to_json(options)methods on the resource serialization by the Rails JSON renderer. They are, therefore, importantto know about, but not part of ActiveModelSerializers.)

What does a 'serializable resource' look like?

An ActiveRecord::Base object.

ActiveModelSerializers provides aActiveModelSerializers::Model,which is a simple serializable PORO (Plain-Old Ruby Object).

ActiveModelSerializers::Model may be used either as a reference implementation, or in production code.

class MyModel ActiveModelSerializers::Model attributes :id, :name, :levelendThe mặc định serializer for MyModel would be MyModelSerializer whether MyModel is anActiveRecord::Base object or not.

Outside of the controller the rules are exactly the same as for records. For example:

render json: MyModel.new(level: 'awesome'), adapter: :jsonwould be serialized the same as

ActiveModelSerializers::SerializableResource.new(MyModel.new(level: 'awesome'), adapter: :json).as_json

Semantic Versioning

This project adheres to semver