Skip to content

Instantly share code, notes, and snippets.

@bosskovic
Created August 19, 2014 18:56
Show Gist options
  • Save bosskovic/f56a7e9e5817357a5d9d to your computer and use it in GitHub Desktop.
Save bosskovic/f56a7e9e5817357a5d9d to your computer and use it in GitHub Desktop.
Rails API versioning
# lib/api_constraints.rb
class ApiConstraints
def initialize(options)
@version = options[:version]
@default = options[:default]
@domain = options[:domain]
end
def matches?(req)
@default || req.headers['Accept'].include?("application/vnd.#{@domain}+json; version=#{@version}")
end
end
# cucumber step for checking the API version
Given /^I send and accept JSON using version (\d+) of the (\w+) API$/ do |version, domain|
header 'Accept', "application/vnd.#{domain}+json; version=#{version}"
header 'Content-Type', 'application/json'
end
require 'api_constraints'
Rails.application.routes.draw do
scope module: :v1, constraints: ApiConstraints.new(version: 1, default: :true, domain: APPLICATION_DOMAIN), defaults: {format: 'json'} do
# resources . . .
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment