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

Fast Rails APIs with representer - Railsberry 2012

Fast Rails APIs with representer - Railsberry 2012

Slides for presentation delivered at Railsberry 2012 in Krakow, where I spoke how to speeding up Rails with faster JSON generation and tweaking Rails.

marcinbunsch

April 23, 2012
Tweet

More Decks by marcinbunsch

Other Decks in Programming

Transcript

  1. class NormalController < ActionController::Base def index @messages = Message.paginate(:page =>

    params[:page]) respond_to do |format| format.json { render :json => @messages } end end end Monday, April 23, 12
  2. class MetalController < ActionController::Metal def index @messages = Message.paginate(:page =>

    params[:page]) self.response_body = @messages.to_json self.status = 200 self.content_type = 'application/json' end end Monday, April 23, 12
  3. class MessageRepresenter < Representer::Base namespace :message attributes :id, :title, :body

    fields :images aggregate :images, :id do |ids, representer| # This is imaginary code!! <3 RemoteApiClient.find_images(ids).group_by(&:message_id) end def images(message) self.aggregated_images[message['id']] end end Monday, April 23, 12
  4. class MessageRepresenter < Representer::Base namespace :message attributes :id, :title, :body

    belongs_to :user has_many :attachments end Monday, April 23, 12
  5. { "message": { "id": 1, "title": "OMG YES", "body": "best

    thing ever" } } Monday, April 23, 12
  6. class MessageRepresenter < Representer::Base namespace :message attributes :id, :title, :body

    belongs_to :user has_many :attachments end class SimpleMessageRepresenter < Representer::Base namespace :post attributes :id, :title, :body end Monday, April 23, 12
  7. describe MessageRepresenter do subject do MessageRepresenter.new([]) end describe "#render" do

    it "renders to json" do subject.render(:json).should == '[]' end end end Monday, April 23, 12
  8. Benchmarking: simple to_json Average: 26ms Benchmarking: active model serializer Average:

    18ms Benchmarking: simple represent Average: 5ms 50 messages with user and one attachment Monday, April 23, 12
  9. Average (ms) 5 18 26 to_json Serializers Representers 50 messages

    with user and one attachment Monday, April 23, 12