Fast Prototyping with Sinatra – A Checklist Aside

If you happen to’re an online designer or developer, you’re effectively acquainted with prototyping. From uncooked wireframing to creating interfaces in Photoshop, designers map out how websites will work earlier than they create them.

Article Continues Under

Over the previous few years, the protoyping course of has modified considerably. With browser makers typically agreeing on net requirements and the rise of instruments reminiscent of Firebug and WebKit’s net inspector, we are able to generally skip Photoshop altogether and go straight to the browser. Plus, JavaScript frameworks like jQuery allow us to play with browser occasions with only some traces of code. However what if we have to do much more? As web sites more and more grow to be net apps, we now have to prototype backend performance, too.

This text introduces Sinatra, a so-called “micro” net framework that helps you create actual (albeit easy) net apps extraordinarily quick, permitting you to prototype flows and behaviors that you could be need to combine right into a last product. Sinatra is written in Ruby, however for our functions we’ll use it because the “glue” between our HTML/CSS and the domain-specific Sinatra capabilities, so that you gained’t need to know a lot quite a lot of easy strategies to get to “Hi there world.” On this article, our instance shall be an very simple Twitter app that accepts two usernames and tells you if one person is following the opposite.

Blurring “entrance finish” and “again finish” and the threshhold of “appness”#section2

Though the phrase “app” will get thrown round lots at the moment, I’d set the boundary between web site and net app on the level the place a person person’s contribution determines the course of occasions on display screen. At first, apps could seem straightforward to prototype as successions of screens; however if you even have a working app, unpredictable conditions all the time reveal themselves. There would possibly, for instance, be completely different homepages for logged in and new customers. A person might have to leap over to a 3rd social gathering web site for authentication earlier than returning. How will you make that as seamless an expertise as attainable? Essential characteristic might come out at you if you (as your first person) get annoyed making an attempt to do one thing. Beginning to mess around with these actions in Sinatra permits you to discover these issues nearly instantly, collapsing the hole between again finish and entrance finish. In case your app attracts from a 3rd social gathering API reasonably than a database, the “again finish” turns into basically boilerplate, and you’ll really use actual knowledge in your mockup as a substitute of laborious coding (the place the temptation to create finest case eventualities all the time lingers).

Sinatra apps make nice proofs of idea and Minimal Viable Merchandise, and generally they’ll even flower into full-blown functions. They’re additionally nice for spinning one thing up extraordinarily shortly throughout breaking information or viral conditions. I ceaselessly spend a number of days on a fast Sinatra app to see if one thing might be carried out with a sure expertise or idea earlier than committing to it. In a phrase, Sinatra is a sort of net designer’s swiss military knife. It doesn’t take lengthy to study, it is useful for prototyping larger tasks, and it’s additionally nice when you should get an online app working shortly with out dwelling a lot on the again finish.

For this tutorial, you’ll have to have Ruby put in. If you happen to’re on a Mac, right here’s an excellent information from Dan Benjamin on establishing Ruby and RubyGems for Snow Leopard. On Home windows, try RubyInstaller, and on Ubuntu Linux run sudo apt-get set up ruby-full. You’ll even have to put in RubyGems, the Ruby bundle supervisor. RubyGems distributes Sinatra and the Twitter gem (a library that enables us to work with the Twitter API). We’ll additionally want to make use of the command line a bit, however simply to put in the libraries, and to begin and cease our app, so don’t fear for those who haven’t used the terminal a lot (although, if you need a crash course, I extremely suggest PeepCode’s Meet the Command Line screencast). Simply know the place it’s—on Mac OS X, it’s Terminal.app within the Utilities folder inside Functions. For the needs of this text, I’ll denote the command line immediate with immediate>. Simply kind the command after the immediate and hit return. Something proven below a immediate> is the output of that command within the terminal.

After you have Ruby and RubyGems put in, you’ll have to open up the Terminal and run:

immediate> sudo gem set up sinatra twitter

Now we have now all of the libraries we’ll want. As soon as that’s carried out, you’ll be able to shut the Terminal.

Organizing a Sinatra app#section4

Now we’re prepared to leap into writing our app. However first, a bit about how Sinatra works. The framework is predicated on the MVC sample, the place a controller mediates between a “mannequin” or a illustration of the information you’re working with, and the view, which is what that knowledge appears to be like like on the entrance finish. A mannequin is often a database, however can actually be any supply of information, reminiscent of an API or person enter saved in a cookie. The vital factor, although, is that it isn’t coupled to its illustration on display screen (or, in MVC lingo, the “view”). A controller talks to each the mannequin and the view to find out what knowledge will get routed the place.

Within the context of prototyping, making a typical HTML/CSS mockup can be simply the V within the MVC, with the information hardcoded in for demo functions. Beginning to consider how the mannequin and controller have an effect on the view is attending to the guts of what makes your new factor an “app.” Your controller can take cues from either side and decide how the information is represented within the view or up to date within the mannequin.

Since Sinatra is a “micro-framework,” it actually solely supplies the “C” and “V” in MVC. It’s agnostic about the way you herald your mannequin. Extra fully-featured net frameworks like Ruby on Rails present all three, with a heavy database layer as effectively. Since we’re going to be grabbing all our knowledge from the Twitter API, our mannequin would be the knowledge it returns—we’ll simply want a number of strategies to request the information we wish and ship it to our controller.

How does a controller work? In Sinatra, it’s merely a listing of HTTP verbs with directions on what to do in response to these verbs. When your browser points a GET command to a Sinatra app with a sure URL sample, it should do no matter is throughout the block that matches the sample.

Right here’s an instance of the world’s easiest Sinatra app.

On the prime of each app file, we’ll put the next two traces to let Ruby comprehend it’s a Sinatra app:

require 'rubygems'
require 'sinatra'

Then, our easy app:

get '/howdy' do
  "Hi there"
finish

All the things between the do and finish are what Sinatra will execute when the browser asks for a URL. On this case if a browser navigates to /howdy, it should show the textual content “Hi there” within the browser. Right here’s a barely extra attention-grabbing instance:

get '/howdy' do
  person = params[:user]  "Hi there " + person + "!"
finish

On this instance, we’re capturing GET question parameters to be handed into our app. If you happen to navigate to /howdy?person=Al on this app, the web page will show “Hi there Al!”

Alternatively, for prettier URLs, the instance might be written like so:

get '/howdy/:person' do
  person = params[:user]  "Hi there " + person + "!"
finish

Then, navigating to /howdy/Al will provide you with the identical end result. To run this app, change to its listing within the Terminal (you would possibly title the app “myapp.rb” for now), and run:

immediate> ruby myapp.rb
== Sinatra/1.0 has taken the stage on 4567 for improvement with 
backup from Skinny
>> Skinny net server (v1.2.7 codename No Hup)
>> Most connections set to 1024
>> Listening on 0.0.0.0:4567, CTRL+C to cease

Now that the native server is working, strive it out by pointing your browser to to http://localhost:4567/howdy/Al. To cease the server, hit control-C (you’ll have to cease and restart the server for those who make any modifications to the code).

What concerning the View?#section5

That is all about including a layer of performance to a static mockup, so how will we interpolate these items into precise HTML? We use views. Sinatra makes this actually easy by searching for recordsdata in a views folder inside your app’s root. In every verb block, you level to a particular view. Right here’s the identical instance with a view:

get '/howdy' do
  @person = params[:user]  erb :howdy
finish

Now in case your app is situated in /myapp/myapp.rb in your file system, you’ll have to put the “howdy” view in /myapp/views/howdy.erb. Right here’s what that file appears to be like like:

<h1>Hi there !</h1>

There’s lots occurring right here. The very first thing you would possibly discover is that we put an @ earlier than our person variable. This turns it into an occasion variable. Occasion variables are vital in Ruby, however for our functions, it’s simply good to know that solely occasion variables might be handed to views. When you’ve got some knowledge inside a verb block that you simply need to present up in a view, retailer it in an occasion variable or it gained’t make that soar.

To name our view, we’re utilizing the erb methodology. ERB stands for embedded ruby—it’s the templating language we’re utilizing to interpolate Ruby into our HTML. By placing erb :howdy because the final line in our verb block, we’re telling Sinatra we need to use ERB to render a template referred to as “howdy.erb” inside our app’s views folder. After we try this, it should know to go all of the occasion variables current in our block into that view.

Working with actual knowledge, the Twitter API#section6

As you’ll be able to see, Sinatra makes it trivially straightforward to create an online app, if the threshhold for “appness” is that it may manipulate person enter. To make it a actual app, we’ll want some knowledge to work with. For that, we’ll pull out the Twitter API by way of the Twitter gem. After this a part of the tutorial, we’ll have an excellent naked bones Twitter app that you should use to drape a stupendous HTML/CSS mockup over.

Let’s make a brand new folder referred to as followapp, and a file inside it referred to as followapp.rb. On this file, we’ll use the identical require statements we had earlier than, however will add another, to incorporate the Twitter library:

require 'rubygems'
require 'twitter'
require 'sinatra'

On this app, we’ll have two “actions”: an index web page which is able to gather the customers we need to test comply with standing on, and a outcomes web page, which is able to show if person A is following person B.

Right here’s what our index motion appears to be like like:

get '/' do  erb :index
finish

As a result of we aren’t doing something within the again finish, all we have now to do is inform Sinatra to level to a sure view. In that view we’ll have a type that collects the person knowledge and submits it to our different motion. Right here’s what the /views/index.erb file appears to be like like:

<h1>Enter two customers</h1>
<type methodology="get">
  Does <enter kind="textual content" title="user1" /> comply with 
  <enter kind="textual content" title="user2" />? <enter kind="submit" worth="Go" />
</type>

As you would possibly anticipate, this submits by way of GET, making a URL that appears like /follows?user1=username&user2=username. To deal with that, we simply create one other motion in our controller that responds to these parameters:

get '/follows' do
  @user1 = params[:user1]
  @user2 = params[:user2]  #not applied but
  @following = is_following?(@user1, @user2)  erb :follows
finish

This motion will deal with the response. It grabs the 2 parameters we’re giving it from the index web page and generates a variable referred to as @following which we haven’t applied but.

I’ll comply with you for those who comply with me#section7

Right here’s how we implement the core engine of the app—the is_following? methodology, which is able to discover out if person one is following person two. Twitter doesn’t make it straightforward to test precisely if one person is following one other, however they do have a followers endpoint of their API which is able to return a listing of person IDs for all of the followers on a sure tài khoản. The one wrinkle to utilizing that is that we have to get a person ID from a display screen title to test it in opposition to that record. For that, we’ll simply use the customers/present endpoint. It’s easy with the Twitter gem. In our app, right here’s the strategy we’ll write:

def twitter_id(screen_name)
  Twitter.person(screen_name).id
finish

That takes a username and returns the person ID. So if I have been to run twitter_id(“a_l”), I’d get 7865282. Now we simply want another methodology, is_following? to check two IDs. Right here’s what that appears like:

def is_following?(a,b)
  followers = Twitter.follower_ids(twitter_id(b)).ids
  followers.embrace?(twitter_id(a))
finish

The Twitter.follower_ids methodology returns an array of person IDs with person B’s followers. We then use embrace? to test if person A’s person ID is current within the array. (For extra on how embrace? and arrays work, see the Ruby Array documentation.) So, with only a few traces of code, we now have the kernel of our app. (Observe, the Twitter.follower_ids methodology solely returns that person’s first 5,000 followers. There are methods to get all of them, however it might complicate the app.) That brings us again to the road in our motion:

@following = is_following?(@user1, @user2)

This occasion variable will then reply true or false as as to whether @user1 is following @user2. What is going to our view appear like? (That is contained in /followapp/views/follows.erb.)

<h2>  

Whew, that’s it! This view will output “Username follows Username” or “Username doesn’t comply with Username.”

The results of running the new Twitter app.

The outcomes of working the brand new Twitter app.

Right here’s your entire “app”:

require 'rubygems'
require 'twitter'
require 'sinatra'def twitter_id(screen_name)
  Twitter.person(screen_name).id
enddef is_following?(a,b)
  followers = Twitter.follower_ids(twitter_id(b)).ids
  followers.embrace?(twitter_id(a))
endget '/' do  erb :index
endget '/follows' do
  @user1 = params[:user1]
  @user2 = params[:user2]  @following = is_following?(@user1, @user2)  erb :follows
finish

Observe: the complete code for this app is on the market on Github.

In about 20 traces of code we have now a working net app that may act as a prototype for a challenge we’re engaged on. Since Sinatra makes it really easy to construct these micro apps, we are able to now prototype performance the best way we used to prototype interface choices. Seeing performance in motion additionally makes it a lot simpler to resolve if this can be a challenge price pursuing. All the things appears to be like glossier in Photoshop comps and even excellent HTML, however if you use an app, you’ll be able to actually inform if that is the suitable highway to be taking place. With Sinatra these choices can come sooner reasonably than later when it’s far more painful to vary course.

After you have an app up and working, you’ll in all probability need to share it. Bear in mind how Sinatra begins up by default at http://localhost:4567? Sharing your app inside a neighborhood community is as straightforward as changing localhost along with your inside IP tackle. Normally this begins with 10.0 or 192.168 and might be present in your community preferences. So, to go round your app inside your workplace or VPN, simply use http://localip:4567.

Sharing your app with the world over the Web is a bit trickier, however not a lot. Absolutely the best method to launch (“deploy”) your app is with a service like Heroku or Engine Yard, that are net hosts designed particularly to run Ruby (Rails and Sinatra) apps and might get you up and working in a short time with little effort. Heroku is free for small apps, making it preferrred to share prototypes, and it has a a lot easier interface. Engine Yard has extra choices, however is a bit tricker and in addition has no free plan. Sadly, most inexpensive shared internet hosting exterior these specialty companies usually are not set as much as host Ruby apps, however your mileage might fluctuate.

Whether or not it’s a prototype, a single serving web site, or one thing extra advanced, it’s all the time a thrill to see even the only app up on the net. Including that “appness” brings life to what have been beforehand simply pages on a server.

There’s far more to Sinatra than I’ve lined right here. To study extra, try a few of these sources:

Leave a Comment