-
-
Save leereilly/987094 to your computer and use it in GitHub Desktop.
API version checking using Sinatra's before filter; supports nested resources
This file contains 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 'sinatra' | |
# Set the version of the API being run here | |
# | |
MAJOR_VERSION = 1 | |
MINOR_VERSION = 0 | |
helpers do | |
def version_compatible?(nums) | |
return MAJOR_VERSION == nums[0].to_i && MINOR_VERSION >= nums[1].to_i | |
end | |
end | |
# Enforce compatibility before the call. Rewrite the | |
# URL in the request to remove the API versioning stuff | |
# | |
before %r{/api/v(\d)\.(\d)} do | |
if version_compatible?(params[:captures]) | |
elements = request.fullpath.split('/') | |
new_path = "" | |
(3..elements.size).each do |i| | |
new_path << "/#{elements[i]}" | |
end | |
request.path_info = new_path | |
else | |
halt 400, "Version not compatible with this server" | |
end | |
end | |
# Reach this route using | |
# http://localhost:4567/api/vX.Y/hello | |
# | |
get '/hello' do | |
"Hello there, compatible client." | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for spotting that one, I appreciate the feedback! -- In the meantime I had found another approach using regex and post_match that I incorporated into https://github.com/oisin/plink but never updated the gist...