Get Off My Lawn

Adventures of a Curmudgeon

Getting to Know Sinatra

For one of my clients I’ve been tasked to create a web-based testing tool that will be used to test a JSON-message-enabled Service. I asked my friends and was pointed to Sinatra.

I perused the website and thought, “Wow, that looks really easy.” So I then started thinking about the requirements for the testing tool. Aside from the pretty bits, the tool has to: 1. send and receive from a socket 2. send and receive json 3. read from the filesystem 4. display printable results (aka the pretty bits) So, in true XP fashion, I set out to build a Spike to research numbers 1 and 2. Aside from the dependencies, I had a no-frills Spike with only 3 files. Not too bad, huh?

Implementation

Dependencies

sudo gem install jsonsudo gem install racksudo gem install sinatra

View Files

layout.erb[sourcecode language=”html”] Frank Frank <%= yield %> [/sourcecode]index.erb[sourcecode language=”html”]Basic NORM Test Harness Line 1: Line 2: City: State: Zip: <%= @result %>[/sourcecode]

Controller

myapp.rb[sourcecode language=”ruby”]# myapp.rbrequire ‘rubygems’require ‘sinatra’require ‘json’server = ‘localhost’port = 40000get ‘/’ do erb :indexendpost ‘/’ do message = { “line1” => params[:line1], “line2” => params[:line2], “city” => params[:city], “state” => params[:state], “zip” => params[:zip] } socket = TCPSocket.new(server, port) socket.puts JSON.generate(message) socket.flush output = “” while(response = socket.gets) output += response end socket.close @result = output erb :indexend[/sourcecode]

No Fuss! No Muss!

I have a feeling any medium to large application will require some careful forethought when using Sinatra. For my purposes though, Sinatra fits the bill. If you have a small-ish application give Sinatra a look; you might be pleasantly surprised how quickly you get up and running.

Cheers!