Skip to content
Alex Sulim edited this page Oct 21, 2015 · 5 revisions

At the most basic level you can serialize objects to JSON directly from the endpoint with the encode helper:

post do
  todo = Todo.create(params)
  status 201
  encode(
    id:    todo.id,
    title: todo.title,
    done:  todo.done)
end

If you find yourself needing to serialize the same object in another file, or sharing helpers to serialize the same attributes, Serializer classes are the way to go.

To create a new one:

$ pliny-generate serializer todo

Then move the logic there:

module Serializers
  class TodoSerializer < Serializers::Base
    structure(:default) do |todo|
      {
        id:    todo.id,
        title: todo.title,
        done:  todo.done
      }
    end
  end
end

You can then update your endpoint to use it:

post do
  todo = Todo.create(params)
  status 201
  encode(serializer.serialize(todo))
end

def serializer
  Serializers::TodoSerializer.new(:default)
end

Notice the serializer can be reused across actions.