Serving static assets with Rack

24 Oct 2014

I think this is a pretty common scenario, and yet I struggled to find an example on how to do it. I was trying to build a single page application using AngularJS on the front-end and Cuba, a minimalistic web framework for Ruby running on top of Rack.

I have a server running a REST API and I want to serve my assets from the same server, to avoid any CORS hassle.

This solution will probably apply to any framework running on top of Rack: Grape, Sinatra and even Rails API.

# This is the config.ru file.

# Serve any requests to the root path ('/') with public/index.html.
use Rack::Static,
  :urls => "/",
  :root => 'public',
  :index => 'index.html'

# Serve requests to assets in /images, /js and /css with public/images, public/js and public/css.
use Rack::Static,
  :urls => ["/images", "/js", "/css"],
  :root => 'public'

# Below is the usual Rack stuff to run your application. Check framework docs for details on this.
require "./my_app"

run MyApp

Notes:

Hope that helps! Cheers!

Thoughts? Comments? Post them to this Reddit thread or hit me up on twitter.