Skip to content

Instantly share code, notes, and snippets.

@teohm
Created June 1, 2011 01:35
Show Gist options
  • Save teohm/1001626 to your computer and use it in GitHub Desktop.
Save teohm/1001626 to your computer and use it in GitHub Desktop.
Using RABL in Rails JSON Web API
# tryrabl/app/views/users/base.rabl
attributes :id, :username, :email, :display_name
# tryrabl/app/views/users/show.rabl
extends "users/base"
object @user
## JSON output:
# {
# "user": {
# "id": 8,
# "username": "blaise",
# "email": "[email protected]",
# "display_name": "Ms. Noe Lowe"
# }
# }
# tryrabl/app/views/users/index.rabl
extends "users/base"
collection @users
## JSON output:
# [{
# "user": {
# "id": 1,
# "username": "alanna",
# "email": "[email protected]",
# "display_name": "Mrs. Gaylord Hoeger"
# }
# }, {
# "user": {
# "id": 2,
# "username": "jarrell.robel",
# "email": "[email protected]",
# "display_name": "Oran Lebsack"
# }
# }]
attributes :id, :title, :description, :start, :end, :location
child :creator => :creator do
extends 'users/base'
end
## JSON output:
# {
# "event": {
# "id": 7,
# "title": "Et earum sed fuga.",
# "description": "Quis sed ..e ad.",
# "start": "2011-05-31T08:31:45Z",
# "end": "2011-06-01T08:31:45Z",
# "location": "Saul Tunnel",
# "creator": {
# "id": 1,
# "username": "alanna",
# "email": "[email protected]",
# "display_name": "Mrs. Gaylord Hoeger"
# }
# }
# }
class GuestsController < ApplicationController
def index
@guests = EventGuest.where(:event_id => params[:event_id])
end
end
# tryrabl/app/views/guests/index.rabl
collection @event_guests
# include the additional attribute
attributes :rsvp
# add child attributes to parent model
glue :user do
extends "users/base"
end
## JSON output:
# [{
# "event_guest": {
# "rsvp": "PENDING",
# "id": 3,
# "username": "myrna_harvey",
# "email": "[email protected]",
# "display_name": "Savion Balistreri"
# }
# }, {
# "event_guest": {
# "rsvp": "PENDING",
# "id": 4,
# "username": "adelle.nader",
# "email": "[email protected]",
# "display_name": "Edgardo Dickens"
# }
# }]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment