Skip to content

Instantly share code, notes, and snippets.

@jhsu
Created October 2, 2012 15:29
Show Gist options
  • Save jhsu/3820162 to your computer and use it in GitHub Desktop.
Save jhsu/3820162 to your computer and use it in GitHub Desktop.
require 'hyper_api'
class Api::BaseController < ApplicationController
respond_to :json
self.responder = Authentication::Responders::HyperApi
end
module Authentication
module Responders
class HyperApi < ActionController::Responder
# Default render for json
#
# Returns the rendered response.
def to_json
render :json => decorated(version).to_json
end
private
# Figure out what version to use based on the Accept header in the format
# of 'application/vnd.something.v1+json' which becomes 'v1'.
#
# Returns the version of the request.
def version
match = @request.headers['Accept'].match(/\.(\w+)\+#{format}/)
if match && version = match[1]
version.capitalize
else
"v1"
end
end
# Try and find a decorator class for the resource.
#
# version - The version of the decorater wanted.
def decorator(version=nil)
name = resource.class.name
Object::const_get("#{name}#{version.to_s.capitalize}Decorator")
rescue NameError
nil
end
# Decorate the resource if possible.
#
# version - The version of the decorator.
def decorated(version=nil)
if decor = decorator(version)
decor.decorate(resource)
else
resource
end
end
end
end
end
module Api
class UsersController < BaseController
def show
user = User.find(params[:id])
respond_with(user)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment