Skip to content

Instantly share code, notes, and snippets.

@CITguy
Last active August 29, 2015 14:01
Show Gist options
  • Save CITguy/20ce9fed8582ff77d1d9 to your computer and use it in GitHub Desktop.
Save CITguy/20ce9fed8582ff77d1d9 to your computer and use it in GitHub Desktop.
Using Rails 4.1 Action Pack variants with Vendor MIME Type for simple API versioning
# config/routes.rb
Rails.application.routes.draw do
# use json if format not defined in url
scope(format: :json) do
get :hello, controller: :sandbox
end
end
# config/initializers/mime_types.rb
# Define a custom Vendor MIME type
Mime::Type.register "application/sandbox-v1+json", :v1json
# app/controllers/sandbox_controller.rb
class SandboxController < ApplicationController
def hello
respond_to do |format|
format.json # hello.jbuilder
format.v1json do
request.variant = :v1 # hello+v1.jbuilder
end
end
end
end
# app/views/sandbox/hello.jbuilder
json.hello "from default json"
# app/views/sandbox/hello+v1.jbuilder
json.hello "from v1 json variant"
# GET [Accept:'application/json', Content-Type:"application/json"] /sandbox/hello
# { "hello":"from default json" }
# GET [Accept:'application/sandbox-v1+json', Content-Type:"application/sandbox-v1+json"] /sandbox/hello
# { "hello":"from v1 json variant" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment