Wednesday, November 4, 2009

Accepting Both Get And Post Method in Sinatra

Whe you would like to accept both GET and POST request with the same block, use the following get_or_post method.

[Before]

require 'rubygems'
require 'sinatra'

get '/' do
  'hi'
end

post '/' do
  'hi'
end

[AFTER]

require 'rubygems'
require 'sinatra'

def get_or_post(path, opts={}, &block)
  get(path, opts, &block)
  post(path, opts, &block)
end

get_or_post '/' do
  'hi'
end

3 comments:

  1. What about :

    require 'rubygems'
    require 'sinatra'

    code = lambda { 'hi' }

    get '/', &code
    post '/', &code

    ReplyDelete
  2. Hello,

    now there's a better way, Sinatra has an extension API: http://www.sinatrarb.com/extensions.html

    So, modern rewrite of get_or_post:

    require 'rubygems'
    require 'sinatra'

    module Sinatra
    module GetOrPost
    def get_or_post(path, options = {}, &block)
    get(path, options, &block)
    post(path, options, &block)
    end
    end

    register GetOrPost
    end

    get_or_post '/' do
    'hi'
    end

    ReplyDelete