StaticAssets Middleware

To install it, run:

sudo gem install wbzyl-sinatra-static-assets -s http://gems.github.com

To use, include it in a Sinatra application:

require 'rubygems'
gem 'static-assets-middleware'
require 'rack/static_assets'

When you will need this gem?

In short, whenever two or more applications are deployed to sub-URI with Phussion Passenger.

This means, that we want these applications to be mounted under one host, http://example.org in the example below:

http://example.org/app1
http://example.org/app2
...
http://example.org/tests/app3
http://example.org/secret/app3
...

See Phusion Passenger users guide, Deploying a Rack-based Ruby application, Deploying to a sub URI.

How to fix broken images/CSS/JavaScript URIs in sub-URI deployments

Some people experience broken images and other broken static assets when they deploy their application to a sub-URI (i.e. http://mysite.com/railsapp/). The reason for this usually is that you used a static URI for your image in the views. This means your img source probably refers to something like /images/foo.jpg. The leading slash means that it's an absolute URI: you're telling the browser to always load http://mysite.com/images/foo.jpg no matter what. The problem is that the image is actually at http://mysite.com/railsapp/images/foo.jpg. There are two ways to fix this.

The second and highly recommended way is to always use Rails helper methods to output tags for static assets. These helper methods automatically take care of prepending the base URI that you've deployed the application to. For images there is image_tag, for JavaScript there is javascript_include_tag and for CSS there is stylesheet_link_tag. In the above example you would simply remove the <img> HTML tag and replace it with inline Ruby like this:

<%= image_tag("foo.jpg") %>

This will generate the proper image tag to

$RAILS_ROOT/public/images/foo.jpg 

so that your images will always work no matter what sub-URI you've deployed to.

Deploying to a sub URI

Add to /etc/hosts:

127.0.0.1       localhost.localdomain localhost sinatra.local

Sym link the application:

ln -s ~/public_git/forks/sinatra-static-assets/examples/app1/public /srv/www/sinatra/app1
ln -s ~/public_git/forks/sinatra-static-assets/examples/app2/public /srv/www/sinatra/app2

Add to /etc/httpd/conf.d/sinatra.conf

<VirtualHost *:80>
  ServerName sinatra.local
  DocumentRoot /srv/www/sinatra

  RackBaseURI /app1
  RackBaseURI /app2
</VirtualHost>

Now, goto to http://sinatra.local/app1 or http://sinatra.local/app2.

TODO

  1. Append a timestamp to the URI to better facilitate HTTP caching. For more information, see the Rails API docs.