Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Bldr: A minimalist JSON templating DSL

Bldr: A minimalist JSON templating DSL

Lighting talk given at Railsconf 2013 on Bldr.

https://github.com/ajsharp/bldr

Alex Sharp

May 01, 2013
Tweet

Other Decks in Programming

Transcript

  1. 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
  2. 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
  3. object :post => @post do attributes :title, :body end {

    "post":{ "title":"my title", "body": "..." } } bldr JSON github.com/ajsharp/bldr Example: objects
  4. 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
  5. bldr JSON collection :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
  6. Rails Sinatra github.com/ajsharp/bldr class PostsController < ApplicationController # GET /posts

    def index @posts = Post.all.limit(10) render :index end end # app/views/posts/index.json.bldr collection :posts => @posts do |post| # ... end class Api::Posts < Sinatra::Application register Sinatra::Bldr get '/posts' do @posts = Post.all.limit(10) bldr :'posts/index' end end # views/posts/index.json.bldr collection :posts => @posts do |post| # ... end Example: Rails / Sinatra