Skip to content

Instantly share code, notes, and snippets.

@amoslanka
Created August 7, 2014 17:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amoslanka/41a46f7f9dec9e644061 to your computer and use it in GitHub Desktop.
Save amoslanka/41a46f7f9dec9e644061 to your computer and use it in GitHub Desktop.
Rack middleware that extracts an API version from either path or accept header.
require 'rack'
module Rack
class ApiVersion
def initialize(app, options = {})
@app = app
@options = options
end
def call(env)
extract_version!(env)
@app.call(env)
end
# 1
# 1.2
# 1.2.3
VERSION_STRING = '(\d+(?:\.\d+)*)'
# /v1/...
PATH_PATTERN = /\/v#{VERSION_STRING}\//i
# application/vnd.foo.bar.v1+xml
# application/vnd.foo.bar.v1.2.3+json
# ...
HTTP_ACCEPT_PATTERN = /.*\.v#{VERSION_STRING}/
private
def extract_version!(env)
path = env['PATH_INFO'] || env['PATH']
version = path.to_s[PATH_PATTERN, 1] ||
env['HTTP_ACCEPT'].to_s[HTTP_ACCEPT_PATTERN, 1] ||
@options[:default_version]
env['api_version'] = version
end
end
module RequestExtensions
def api_version
@env['api_version']
end
end
end
Rack::Request.send(:include, Rack::RequestExtensions)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment