Bldr: A Minimalist JSON Templating DSL
-
Upload
alex-sharp -
Category
Technology
-
view
667 -
download
1
description
Transcript of Bldr: A Minimalist JSON Templating DSL
BldrA minimalist JSON templating DSL
github.com/ajsharp/bldr
github.com/ajsharp/bldr
github.com/ajsharp/bldr
github.com/ajsharp/bldr
What?• Produce JSON from ruby objects
• 4 core API methods
• Treat json API responses as a view layer concern
• Support for rack/sinatra and rails 3.2
• In production use at Zaarly for ~2 years
Bldr in a nutshell
github.com/ajsharp/bldr
Why?• Rails is a great framework for building API services
• But #as_json is not for serving prod-ready json
• APIs are not intuitive for other json templating engines
• See: rabl, json_builder, et al
object :post => @post do
attributes :title, :body
end
{
"post":{
"title":"my title",
"body": "..."
}
}
bldr JSON
github.com/ajsharp/bldr
Example: objects
bldr JSON
collection :posts => @posts do |post|
attributes :title, :body
attribute(:created_at) {
post.created_at.iso8601
}
end
{"posts": [
{
"title": "Railsconf 2013 wrap-up",
"body": "...",
"created_at": "2013-05-01T14:18:16-07:00"
},
{
"title": "OMG Railsconf is coming up!",
"body": "...",
"created_at": "2013-04-20T08:01:12-07:00"
}
]}
github.com/ajsharp/bldr
Example: collections
bldr JSONcollection :posts => @posts do |post|
attributes :title, :body
attribute(:created_at) { post.created_at.iso8601 }
collection :comments => post.comments do |comment|
attributes(:author_name)
attribute(:body) {
HTML::Whitelister.clean(comment.body)
}
end
end
{"posts": [{
"title": "Railsconf 2013 wrap-up",
"body": "...",
"created_at": "2013-05-01T14:18:16-07:00",
"comments":[
{
"author_name": "Bob Bobberson",
"body": "ohai!"
}
]
}]
}
github.com/ajsharp/bldr
Example: nested collections
Rails Sinatra
github.com/ajsharp/bldr
class PostsController < ApplicationController # GET /posts def index @posts = Post.all.limit(10) render :index endend
# app/views/posts/index.json.bldrcollection :posts => @posts do |post| # ...end
class Api::Posts < Sinatra::Application register Sinatra::Bldr
get '/posts' do @posts = Post.all.limit(10) bldr :'posts/index' endend
# views/posts/index.json.bldrcollection :posts => @posts do |post| # ...end
Example: Rails / Sinatra
twitter @ajsharpweb alexjsharp.com
github.com/ajsharp/bldr