-
Notifications
You must be signed in to change notification settings - Fork 75
Serialization
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)
endIf 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
endYou 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)
endNotice the serializer can be reused across actions.
Basics
Diving in
- bin/setup
- Config
- CORS
- Endpoints
- Error Handling
- Logging
- Models
- Mediators
- Migrations
- Rake Tasks
- Request IDs
- RequestStore
- Schema
- Serialization
- Testing
- Updating
Guides