No F*cking Idea

Common answer to everything

Api Prototyping With Rails Respond_with

| Comments

Prototyping json / xml RESTfull api with rails is easy. Before we will want to rewrite it to something like erlang webmachine or node.js! For purpose of this we can use syntax introduced in rails 3. (ages ago) with respond_to/respond_with it is very cool.

Example controller

How we use this ? Lets take a peek and simple example:

1
2
3
4
5
6
7
8
9
class VenuesController < ApplicationController

  respond_to :html, :xml, :json

  def index
    respond_with(@venues = Venue.all.page(params[:page]).per(20))
  end

end

Two things we will notice at start is respond_to :html, :xml, :json this is something like old merbs provides where we specify to which formats we want to respond. Second change is how we layout the action. All we have to do is to put into respond_with object we want to respond with.

What this buys for us ?

  • If we have html request to actions like create, update or destroy we want to redirect on success
  • if we have json, xml request to same type of “state changing” actions we want to render response with our format.

We achieve both of this with reponds_with in just one line. But lets take a peek at longer example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class VenuesController < ApplicationController

  before_filter :authenticate_user!, :except => [:index, :show, :near]

  respond_to :html, :xml, :json

  def index
    respond_with(@venues = Venue.all.page(params[:page]).per(20))
  end

  def show
    respond_with(@venue = Venue.find_by(permalink: params[:id]))
  end

  def new
    repond_with(@venue = Venue.new)
  end

  def create
    @venue = Venue.create(params[:venue])
    respond_with(@venue, :location => venues_url)
  end


end

In this example we can see example of create action where we add :location => venues_url this will in case of format: html success redirect to this url.

Summary

Using this helps to write stuff fast and readable, you can still use plain old respond_to in action with old format.html syntax..

I hope you liked it :)

Comments