One way of handling assets in Sinatra is to use Sprockets.
First install sprockets:
gem install sprockets
or add sprockets gem to your Gemfile:
You will need an instance of the Sprockets::Environment class to access and serve assets from your application:
environment = Sprockets::Environment.new
and append all desired assets paths:
A good way to do this is with the map method in
But you could also set it in you main application file or add sinatra extension.
The Sprockets Environment has methods for retrieving and serving assets, manipulating the load path, and registering processors. It is also a Rack application that can be mounted at a URL to serve assets over HTTP.
Now you can keep your files under defined directories:
If you would like to compress your assets use compressor of your choice:
environment.js_compressor = :uglify environment.css_compressor = :scss
Don't forget to add uglifier and sass gems to your Gemfile.
Example minifiers and required gems: *
:yui (gem 'yui-compressor') *
:closure (gem 'closure-compiler') *
:jsmin (gem 'jsmin') *
Update your layout file:
<!-- app/views/layout.erb --> <head> ... <link rel="stylesheet" href="assets/app.css"> <script src="assets/app.js"></script> </head>
Note that you need to add only core files
app.css. These very files will be compiled by the Sprockets
If you would like to use asset_path helpers check sprocket helpers gem.
Sprockets allows you to use various directives:
It will require all files alphabetically. But if you would like to add
files individually remove
require_tree . and add each file:
Adding CSS files works identically, but in the respective CSS configuration file.
// app/assets/stylesheets/app.css //= require bootstrap.css
Sprockets directives can begin with
/*= */ .
Summing up, your main application file may look like this:
# app/config.ru require './app' run MyApp.new
For more information visit: