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:
- send and receive from a socket
- send and receive json
- read from the filesystem
- 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 json
sudo gem install rack
sudo gem install sinatra
View Files
layout.erb
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<title>Frank</title>
</head>
<body>
<div class="container">
<div id="header">
<h1>Frank</h1>
</div>
<div id="content">
<%= yield %>
</div>
</div>
</body>
</html>
index.erb
<h2>Basic NORM Test Harness</h2>
<form action="/" method="post" accept-charset="utf-8">
<p><label for="line1">Line 1: </label><input type="text" name="line1" value="" id="line1"></p>
<p><label for="line2">Line 2: </label><input type="text" name="line2" value="" id="line2"></p>
<p><label for="city">City: </label><input type="text" name="city" value="" id="city"></p>
<p><label for="state">State: </label><input type="text" name="state" value="" id="state"></p>
<p><label for="zip">Zip: </label><input type="text" name="zip" value="" id="zip"></p>
<p><input type="submit" value="Continue →"></p>
</form>
<div>
<pre><%= @result %></pre>
</div>
Controller
myapp.rb
# myapp.rb
require 'rubygems'
require 'sinatra'
require 'json'
server = 'localhost'
port = 40000
get '/' do
erb :index
end
post '/' 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 :index
end
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!