the best way to serve static files from Sinatra

Categories Development, Uncategorized

I’ve been using Ruby for a couple of years now, mostly for utility scripts (organizing family pictures, generating XML files, processing CSV files… it’s good for these types of things) and for web prototypes but lately I’ve started to get the taste of it.

Back to the point. I was just about to tell you how to serve static files from Sinatra. For those of you that are not familiar with Sinatra, it’s a simple and beautiful MVC framework for non-Rails web apps (whatever that means).

The simplest way to serve static files from Sinatra is don’t. I’ve looked at the tutorials, I’ve read the stackoverflow answers and all the solutions and workarounds are either ugly (complicated, twisted), inefficient(reading and serving files through controllers) or just don’t work (that public folder thing… didn’t work).

So, the best way to server static files from Sinatra is actually to serve them from Rack 🙂

So, here is how it goes:

  1. You don’t serve static files from Sinatra, just business
  2. You run Sinatra on top of Rack (as you should), configuring everything in config.ru
  3. You let passenger or thin or whatever you use handle the rackup (I use thin)
  4. Done

This way it’s faster, and safer (who knows what kind of buggy code you might churn up to serve files).

Enough for the chatter, here’s the mapping that you can do in config.ru:

#map a directory including a directory listing
map "/js" do
	run Rack::Directory.new("./resources/js")
end

# map just one file
map "/favicon.ico" do
	run Rack::File.new("./resources/favicon.ico")
end

Now remember you’ll need the rack gems but if you require “thin” in your Gemfile, rack will be included as well.

I like the expressiveness and simplicity of Ruby code, especially poetry mode, and as I venture through the language and frameworks I thought it would be nice to share some things.

3 thoughts on “the best way to serve static files from Sinatra

Leave a Reply

Your email address will not be published. Required fields are marked *