Created
October 2, 2012 15:29
-
-
Save jhsu/3820162 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'hyper_api' | |
class Api::BaseController < ApplicationController | |
respond_to :json | |
self.responder = Authentication::Responders::HyperApi | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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