Bldr: A Minimalist JSON Templating DSL

9
Bldr A minimalist JSON templating DSL github.com/ajsharp/bldr

description

Lightning talk from Railsconf 2013. https://github.com/ajsharp/bldr

Transcript of Bldr: A Minimalist JSON Templating DSL

Page 1: Bldr: A Minimalist JSON Templating DSL

BldrA minimalist JSON templating DSL

github.com/ajsharp/bldr

Page 2: Bldr: A Minimalist JSON Templating DSL

github.com/ajsharp/bldr

github.com/ajsharp/bldr

Page 3: Bldr: A Minimalist JSON Templating DSL

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

Page 4: Bldr: A Minimalist JSON Templating DSL

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

Page 5: Bldr: A Minimalist JSON Templating DSL

object :post => @post do

attributes :title, :body

end

{

"post":{

"title":"my title",

"body": "..."

}

}

bldr JSON

github.com/ajsharp/bldr

Example: objects

Page 6: Bldr: A Minimalist JSON Templating DSL

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

Page 7: Bldr: A Minimalist JSON Templating DSL

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

Page 8: Bldr: A Minimalist JSON Templating DSL

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

Page 9: Bldr: A Minimalist JSON Templating DSL

twitter @ajsharpweb alexjsharp.com

github.com/ajsharp/bldr