Search code examples
rubyhttpsinatramongrelwebrick

What is the easiest servlet library in ruby?


What framework do you recommand for writing simple web applications in ruby, between WebRick, Mongrel and Sinatra ?

I would like to answer in json to requests from a client. I would like to have my own code decoupled from the Http framework as much as possible.

Do you know any other framework ?


Solution

  • WEBrick and Mongrel are servers, not frameworks for building web applications. As such, they have APIs that are lower level and tied to their own idiosyncrasies which makes them a bad place to start if you want to design your web application so that it can run on different servers.

    I would look for a framework that builds on Rack, which is the standard base layer for building web apps and web frameworks in Ruby these days.

    If you are making something really simple, learning Rack's interface by itself is a good place to start.

    E.G., a Rack Application that parses json out of a post request's body and prints it back out prettified.

    # in a file named config.ru
    require 'json'
    class JSONPrettyPrinterPrinter
      def call env
        request  = Rack::Request.new env
        if request.post?
          object = JSON.parse request.body
          [200, {}, [JSON.pretty_generate(object)]]
        else
          [200, {}, ["nothing to see here"]]
        end
      end
    end
    
    run JSONPrettyPrinterPrinter
    

    you can run it by running rackup in the same dir as the file.

    Or, if you want something a bit more high level, you can use sinatra, which looks like this

    require 'sinatra'
    
    post '/' do
      object = JSON.parse request.body
      JSON.pretty_generate(object)
    end
    

    Sinatra's README is a good introduction to it's features.