Created
August 7, 2014 17:38
-
-
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.
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 '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