ActiveModelSerializers (AMS)

repository·master·Indexed 26 days ago

https://github.com/rails-api/active_model_serializers

A library for serializing Ruby objects into JSON, commonly used in Rails applications to provide structured API responses. It supports various serialization formats, including JSON:API, and provides features for attribute filtering, caching, conditional attributes, and polymorphic associations. The library supports multiple stable versions (0.8, 0.9, and 0.10) and provides a Model class for serializing Plain Old Ruby Objects (POROs).

Tokens
2K
Snippets
3
Records
27
Agent score
89%

What's inside ActiveModelSerializers

  1. Understand the development status of AMS

    master

    ActiveModelSerializers is currently undergoing significant architectural changes.

    • 0.10.x Maintenance: The 0-10-stable branch is being maintained for stability, but active development is limited. A future 0.11.x release may be created to remove deprecations.
    • Future Direction: The next major release aims to move away from implicit behavior (like automatic serializer guessing) toward an explicit model. The design focuses on a one-to-many relationship between models and serializers, primarily defining JSON:API resource objects (id, type, attributes, and relationships) with an as_json method.
    • Master Branch: The master branch is currently in a state of renovation and does not have a released version.
  2. Use inline syntax for attributes and associations

    master

    To avoid method name conflicts and enable dynamic values, use the inline block syntax for defining attributes and associations. This approach removes dynamically defined methods on the serializer.

    Attributes You can define an attribute with a block to return a custom value:

    attribute :title do 'Mr. Topum Hat' end

    Associations You can define associations with blocks. Note that in version 0.10.x, association blocks are evaluated in the serializer scope, so you must use object to access the resource being serialized.

    Dynamic Associations You can pass dynamic data to associations using the virtual_value option:

    has_many :reviews, virtual_value: [{ id: 1 }, { id: 2 }]
    attribute :title do 'Mr. Topum Hat' end
    
    # Note: Association blocks use serializer scope
    has_many :titles do object.customers.pluck(:title) end
    
    # Dynamic associations
    has_many :reviews, virtual_value: [{ id: 1 }, { id: 2 }]
  3. Configure Serializer namespaces and prefixes

    master

    The 0.9.0 series introduced a CONFIG object and several namespace management features:

    • Namespace Lookup: Serializers for associations are looked up in the parent serializer's namespace first.
    • Prefix Option: Use a prefix option to specify a different version or namespace for a serializer.
    • Default Options: The default_serializer_options can be set to define a default namespace that is inherited by associations.