Using Sinatra for local Javascript development

For a little while now, I’ve been playing with Sammy.js, a small framework built on top of jQuery which makes it easier for you to develop single-page web apps. More specifically, the storage plug-in for it looks interesting, with JSON-serialization support and support for the KeyValueObserver pattern.

I started playing with Sammy.js with simple local files, and it worked out-of-the-box. But when I tried the storage plug-in, it just didn’t work at all. When you look at the source code for the plug-in, you get a hint of why:

isAvailable: function() {
    return ('localStorage' in window) &&
        (window.location.protocol != 'file:');

I was running on the file:// protocol (since I didn’t had a web server started on my machine), which was why the feature wasn’t available. But why is the plug-in checking for the file:// protocol anyway? Well, if you remove the check and try to run the code in Firefox, you will see that nothing has changed, since Firefox will prevent you from using the local storage if you’re running the script from a local file, probably for security reasons (but in Chrome it worked fine though). So to use this feature on Firefox, you have to serve the file from a web server.

Another example when it’s unwise to use the file:// protocol is when you’re using $.get() to access a resource, i.e. a Javascript template or some static JSON. If that was permitted, it would mean a major security issue for web files accessed locally.

So, it seems like we need to start up a web server and use http://localhost instead. How could I do this in the most simplest way? Use Sinatra!

Sinatra is a DSL for quickly creating web applications in Ruby with minimal effort

Though, we will not use any feature of the DSL, since we’re only going to serve static files.

First, install Ruby (including rubygems), and type 'gem install sinatra' in a shell. Then, create a folder named ‘public’, drop your local files there and navigate one step up in the file hierarchy ('cd ..'). Now, create a ruby file containing the following:

require 'rubygems'
require 'sinatra'

Start the web server with 'ruby your_saved_file.rb'. Now you can try your web app on http://localhost:4567/a_file_in_the_public_folder.html


Leave a Reply