0
JSON?
- JavaScript Object Notation
- A datastructure for talking between servers/clients/other servers
- Key value pairs
- Universal, straightforward, human readable.
{
"key1": "value1",
"key2": 2,
"key3": {
"key3a": "nested"
}
}
JSON Template?
- Build a sensible format for handling JSON
- Is treated a bit like a view
- Gives a handy DSL
- Only exposes the data you want
RABL
- Ruby API Builder Language
- gem 'rabl'
- Sinatra/Padrino : Rabl.register!
- Just call render from controller
RABL Template
# app/views/posts/index.rabl
collection @posts
attributes :id, :title, :subject
child(:user) { attributes :full_name }
node(:read) { |post| post.read_by?(@user) }
Naming
object @user => :person
# => { "person" : { ... } }
collection @users => :people
# => { "people" : [ { "person" : { ... } } ] }
collection @users, root: "people", object_root: "user"
# => { "people" : [ { "user" : { ... } } ] }
Attributes/Blocks
attributes :bar => :baz, :dog => :animal
# => # { baz : , animal : }
node :full_name do |u|
u.first_name + " " + u.last_name
end
Partials
node :location do
{ :city => @city,
:address => partial("users/address", :object => @address) }
end
Deep Nesting
# app/views/quizzes/show.json.rabl
object @quiz
attribute :title
child :questions do
attribute :caption
child :answers do
# Use inheritance to reduce duplication
extends "answers/item"
end
end
Alternatives
- JSONify
- Jbuilder
- RepresentationView
- Active Model Serializers
Advantages
- A single place to check your api format
- Tidies up your controllers
- Stops 'munging' of data in controllers
- Quick api specific changes.
Questions?
@atleastimtrying