Serializing

class UserSerializer < Serega
  attribute :username
  attribute :posts, serializer: PostSerializer
end

UserSerializer.to_h(user)
# => {username: "batman", posts: [{title: "Gotham at night"}]}

UserSerializer.to_h([user])
# => [{username: "batman", posts: [{title: "Gotham at night"}]}]

UserSerializer.to_h(nil) # => nil

.call is an alias of .to_h. Both accept the field selection options :only, :except and :with, and the serialization options:

The options are keyword arguments. Pass a Hash of options with **:

UserSerializer.to_h(user, **options)

An unknown option raises ArgumentError. With plugin :root or plugin :context_metadata, it raises Serega::SeregaError.

JSON

.to_json returns a JSON String: JSON.generate of the .to_h result. It takes the same options as .to_h.

UserSerializer.to_json(user)
# => "{\"username\":\"batman\",\"posts\":[{\"title\":\"Gotham at night\"}]}"

render json: UserSerializer.to_json(user) # Rails renders the String as it is

To encode with another JSON library, pass it the .to_h result:

Oj.dump(UserSerializer.to_h(user), mode: :compat)

Struct and Data results

.to_struct returns Struct objects and .to_data returns Data objects, nested relations included. .to_struct is as fast as .to_h.

UserSerializer.to_struct(user)
# => #<struct username="batman", posts=[#<struct title="Gotham at night">]>

UserSerializer.to_data(user)
# => #<data username="batman", posts=[#<data title="Gotham at night">]>

UserSerializer.to_data(user).posts.first.title # => "Gotham at night"

An attribute named initialize or a name that Ruby does not accept as a member, for example name=, raises Serega::SeregaError. A member named like a method of Struct or Data, for example hash, replaces this method in the result.

Reusing a serializer

A serializer instance prepares its serialization plan once. Reuse it to serialize many times with the same fields. Its methods take the serialization options:

serializer = UserSerializer.new(only: [:username])
serializer.to_h(user, many: false)
serializer.to_json(users, context: {current_user: current_user})

Class methods cache plans too: config.max_cached_plans_per_serializer_count keeps up to 20 plans per serializer by default. See Configuration.