Skip to content

Instantly share code, notes, and snippets.

@smtalim
Created July 12, 2013 04:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smtalim/5981342 to your computer and use it in GitHub Desktop.
Save smtalim/5981342 to your computer and use it in GitHub Desktop.
Let us say that our app requires us to send both GET and POST requests to a particular URL such that the same block of code handles both verbs. It makes sense to define an extension that can handle our requirement, as we don’t want to define two routes with identical code.
** Creating Sinatra Extensions **
Let us say that our app requires us to send both GET and POST requests to a particular URL such that the same block of code handles both verbs. It makes sense to define an extension that can handle our requirement, as we don’t want to define two routes with identical code.
Here is our code:
# post_get.rb
require 'sinatra/base'
module Sinatra
module PostGet
def post_get(route, &block)
get(route, &block)
post(route, &block)
end
end
# now we just need to register it via Sinatra::Base
register PostGet
end
Note: When creating extension and helper methods (as above), it’s considered a best practice to wrap those in a module and use the register method to let Sinatra figure out where to use those modules as mixins.
To use our custom Sinatra::PostGet extension, write this code:
# test.rb
require 'sinatra'
require './sinatra/post_get'
post_get '/' do
"Hi #{params[:name]}"
end
Open a command window and run our Sinatra app:
$ ruby test.rb
INFO WEBrick 1.3.1
INFO ruby 2.0.0 (2013-05-14) [i386-mingw32]
== Sinatra/1.4.3 has taken the stage on 4567 for development with backup from WEBrick
INFO WEBrick::HTTPServer#start: pid=6964 port=4567
Let's use cURL to send a GET request to our app. Open another command window and type:
$ curl -G http://localhost:4567
Hi world!
On the server console, you will see something like this:
127.0.0.1 - - [12/Jul/2013 09:17:57] "GET / HTTP/1.1" 200 9 0.0030
TALIM-PC - - [12/Jul/2013:09:17:57 India Standard Time] "GET / HTTP/1.1" 200 9
Now let's use cURL to send a POST request to our app:
$ curl -d hello http://localhost:4567
Hi world!
On the server console, you will see something like this:
127.0.0.1 - - [12/Jul/2013 09:19:58] "POST / HTTP/1.1" 200 9 0.0010
TALIM-PC - - [12/Jul/2013:09:19:58 India Standard Time] "POST / HTTP/1.1" 200 9
Success! We now have a custom extension that allows us to respond to two verbs in one route without duplicating any code.
Hat Tip: Konstantin Haase
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment