Created
May 2, 2011 23:36
-
-
Save oisin/952572 to your computer and use it in GitHub Desktop.
API version checking using Sinatra's before filter
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]) | |
target = request.fullpath.split('/').last | |
request.path_info = "/#{target}" | |
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 |
Thanks! That was a bit of a miss in my gist for sure - I incorporated the snippet into an application and replaced the code for munging the URL to use regex and post_match() - this gives you the piece of the string that _hasn't_ been matched by the regex, which is ideal.
Appreciate the update - I've added another fork to the gist with the post_match() approach and updated the blog entry....
…--oh
##
Oisin Hurley
[email protected]
On Monday 23 May 2011 at 18:52, leereilly wrote:
Thanks for this. I had problems further down the resource chain i.e. `http://localhost:4567/api/people/` would work using this code, but `http://localhost:4567/api/people/1/phones/23/` would not. I put a small fix together @ https://gist.github.com/987094 that allows for nested resources.
##
Reply to this email directly or view it on GitHub:
https://gist.github.com/952572
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this. I had problems further down the resource chain i.e.
http://localhost:4567/api/people/
would work using this code, buthttp://localhost:4567/api/people/1/phones/23/
would not. I put a small fix together @ https://gist.github.com/987094 that allows for nested resources.