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

Ajax and Rails

Ajax and Rails

Presentation given during the genevarb meetup, in Geneva (Switzerland)

Vincent Pochet

December 12, 2012
Tweet

More Decks by Vincent Pochet

Other Decks in Programming

Transcript

  1. Ajax and Rails
    by Vincent Pochet
    @vin100pochet
    https://github.com/vincent-pochet

    View Slide

  2. Ajax and Rails
    ● Standard rendering
    ● json messages
    ○ as_json
    ○ json templates
    ● Rendering HTML
    ○ pjax
    ○ turbolinks

    View Slide

  3. Standard rendering
    The old way!
    Each action render the full page markup:
    ● layout
    ● external scripts and css files
    ● page content
    A POST action send data and receive response as a new
    HTML page => full rendering on every action

    View Slide

  4. as_json
    Model Controller
    class Model < ActiveRecord::Base
    def as_json(options = {})
    super({only: [:id, :name]}.merge!(options))
    end
    end
    class ModelsController < ApplicationController
    def show
    model = Model.find(params[:id])
    render json: model
    end
    end
    Easy for simple data/message transfer
    Did not scale (multiple output format...)
    Models should not be responsible of their presentation

    View Slide

  5. The MVC way
    jbuilder
    Model
    View (show.json.jbuilder)
    Controller
    class Model < ActiveRecord::Base
    end
    json.(@model, :id, :name)
    json.other @model.compute_something
    class ModelsController < ApplicationController
    def show
    @model = Model.find(params[:id])
    end
    end
    We use templates like we do for html rendering
    Partial templates
    Multiple presentation for models, depending of the action
    Advanced rendering

    View Slide

  6. The MVC way
    jbuilder (json)
    https://github.com/rails/jbuilder
    Builder (xml)
    https://github.com/jimweirich/builder
    rabl (json and xml)
    https://github.com/nesquena/rabl

    View Slide

  7. HTML rendering
    PJAX (https://github.com/defunkt/jquery-pjax)
    HTML / Javascript Controller
    class ModelsController < ApplicationController
    def show
    @model = Model.find(params[:id])
    render layout: false if request.headers['X-PJAX']
    end
    end
    Simple jquery extension
    Reload only portions of web pages on navigation
    PushState support
    You keep the control on how links are rendered
    Explore
    <br/>$(document).pjax('a[data-pjax]');<br/></scrript><br/>

    View Slide

  8. HTML rendering
    Turbolinks (https://github.com/rails/turbolinks)
    Mix of the standard HTML rendering with a javascript based
    application.
    Similar to PJAX with differences:
    ● A rails project (part of Rails 4)
    ● Replace the entire body and the title tag content
    ● Not dependant on jQuery
    ● Used by default for all internal links

    View Slide

  9. Questions
    ?

    View Slide