Skip to content

Instantly share code, notes, and snippets.

@grassdog
Created December 12, 2012 13:37
Show Gist options
  • Save grassdog/4267767 to your computer and use it in GitHub Desktop.
Save grassdog/4267767 to your computer and use it in GitHub Desktop.
An example of a JSON presenter. It uses the Representative gem for JSON rendering.
class Goal < ActiveRecord::Base
belongs_to :user
has_many :checkpoints
# Fields from schema.rb
#create_table "goals", :force => true do |t|
# t.string "description"
# t.string "period"
# t.integer "user_id"
# t.integer "position"
# t.datetime "created_at"
# t.datetime "updated_at"
#end
end
class Api::GoalsController < ApplicationController
respond_to :json
before_filter :authenticate_user!
def index
goals = GoalsPresenter.new(current_user.goals, TimeSpan::Fortnight.new(Date.today))
respond_to do |format|
format.json { render :json => goals.to_json }
end
end
end
require 'representative/json'
class GoalsPresenter < DelegateClass(Array)
def initialize(goals, span)
@goals = goals
@span = span
super(@goals)
end
def to_json
json = Representative::Json.new do |r|
r.list_of(:goals, @goals) do |goal|
r.element :description
r.element :position
r.element :period
r.element :created_at, goal.created_at
r.element :id
r.element :history, "history" do
r.element :start_date, @span.start_date
r.element :end_date, @span.end_date
r.list_of(:checkpoints, goal.checkpoints.in_timespan(@span).in_date_order) do |checkpoint|
r.element :date
r.element :achieved
r.element :description
r.element :created_at, checkpoint.created_at
r.element :id
end
end
end
end
json.to_s
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment