• Stars
    star
    542
  • Rank 78,754 (Top 2 %)
  • Language
    CSS
  • License
    MIT License
  • Created over 12 years ago
  • Updated over 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Package your assets transparently in Sinatra.

WARNING : This repo is not maintained anymore!

See sprocket-based alternatives like sinatra-asset-pipeline and sprockets-helpers.

Sinatra AssetPack

The most convenient way to manage your assets in Sinatra.

Build Status Gem Version Dependency Status Code Climate

Installation

# Gemfile
gem 'sinatra-assetpack', :require => 'sinatra/assetpack'

Setup

Register the extension and set your assets configuration.

require 'sinatra/base'
require 'sinatra/assetpack'

class App < Sinatra::Base
  set :root, File.dirname(__FILE__) # You must set app root

  register Sinatra::AssetPack

  assets {
    serve '/js',     from: 'app/js'        # Default
    serve '/css',    from: 'app/css'       # Default
    serve '/images', from: 'app/images'    # Default

    # The second parameter defines where the compressed version will be served.
    # (Note: that parameter is optional, AssetPack will figure it out.)
    # The final parameter is an array of glob patterns defining the contents
    # of the package (as matched on the public URIs, not the filesystem)
    js :app, '/js/app.js', [
      '/js/vendor/**/*.js',
      '/js/lib/**/*.js'
    ]

    css :application, '/css/application.css', [
      '/css/screen.css'
    ]

    js_compression  :jsmin    # :jsmin | :yui | :closure | :uglify
    css_compression :simple   # :simple | :sass | :yui | :sqwish
  }
end

Usage

  1. Drop your assets into /app/css, /app/js, /app/images.
  2. Add register Sinatra::AssetPack (see setup options).
  3. Use <%= js :app %> and <%= css :application %> in your layout.
  4. You now have proper assets management!

Using in layouts

In your layouts, use the css and js helpers:

# layout.erb
<%= css :application, :media => 'screen' %>
<%= js  :app %>
# layout.haml
!= css :application, :media => 'screen'
!= js :app

Results

Development mode

If you're on development mode, it serves each of the files as so:

<link rel='stylesheet' href='/css/screen.849289.css' media='screen' type='text/css' />
<script type='text/javascript' src='/js/vendor/jquery.283479.js'></script>
<script type='text/javascript' src='/js/vendor/underscore.589491.js'></script>
<script type='text/javascript' src='/js/app/main.589491.js'></script>

Production mode

If you're on production mode, it serves a compressed version in the URLs you specify:

<link rel='stylesheet' href='/css/application.849289.css' media='screen' type='text/css' />
<script type='text/javascript' src='/js/app.589491.js'></script>

Features

  • CoffeeScript support Just add your coffee files in one of the paths served (in the example, app/js/hello.coffee) and they will be available as JS files (http://localhost:4567/js/hello.js).

  • Sass/Less/SCSS support Works the same way. Place your dynamic CSS files in there (say, app/css/screen.sass) and they will be available as CSS files (http://localhost:4567/css/screen.css).

  • Cache busting the css and js helpers automatically ensures the URL is based on when the file was last modified. The URL /js/jquery.js may be translated to /js/jquery.8237898.js to ensure visitors always get the latest version.

  • Images support Image filenames in your CSS will automatically get a cache-busting suffix (eg, /images/icon.742958.png).

  • Embedded images support You can embed images in your CSS files as data: URIs by simply adding ?embed to the end of your URL.

  • No intermediate files needed You don't need to generate compiled files. You can, but it's optional. Keeps your source repo clean!

  • Auto minification (with caching) JS and CSS files will be compressed as needed.

  • Heroku support Oh yes. That's right.

Compressors

By default, AssetPack uses JSMin for JS compression, and simple regexes for CSS compression. You can specify other compressors in the assets block:

assets {
  js_compression  :jsmin    # :jsmin | :yui | :closure | :uglify
  css_compression :simple   # :simple | :sass | :yui | :sqwish
}

YUI Compressor

This uses Yahoo's Java-powered YUI compressor.

assets {
  js_compression  :yui
  js_compression  :yui, :munge => true   # Munge variable names

  css_compression :yui
}

Note: This depends on the yui-compressor gem :

# Gemfile
gem 'yui-compressor', :require => 'yui/compressor'

SASS compression

This treats the CSS files as Scss files and uses Sass's :output => :compressed.

assets {
  css_compression :sass
}

Note: This depends on the sass gem :

# Gemfile
gem 'sass'

Sqwish CSS compression

Sqwish is a NodeJS-based CSS compressor. To use Sqwish with AssetPack, install it using npm install -g sqwish. You need NodeJS and NPM installed.

assets {
  css_compression :sqwish
  css_compression :sqwish, :strict => true
}

Google Closure compression

This uses the Google closure compiler service to compress your JavaScript. Available levels are:

  • WHITESPACE_ONLY
  • SIMPLE_OPTIMIZATIONS
  • ADVANCED_OPTIMIZATIONS
assets {
  js_compression :closure
  js_compression :closure, :level => "SIMPLE_OPTIMIZATIONS"
}

UglifyJS compression

This uses the UglifyJS compressor to compress your JavaScript. You will need to install the uglifier gem.

For options, refer to the Uglifier documentation.

assets {
  js_compression :uglify
  js_compression :uglify, [options]
}

Note: This depends on the uglifier gem :

# Gemfile
gem 'uglifier'

Images

To show images, use the img helper. This automatically adds width, height, and a cache buster thingie. ImageMagick is required to generate full image tags with width and height.

<!-- Original: --> <%= img '/images/email.png' %>
<!-- Output:   --> <img src='/images/email.873842.png' width='16' height='16' />

URL translation

In your CSS files, url()'s will automatically be translated.

/* Original: */    .email { background: url(/images/email.png); }
/* Output:   */    .email { background: url(/images/email.6783478.png); }

Image embedding

Want to embed images as data: URI's? Sure! Just add ?embed at the end of the URL.

/* Original: */    .email { background: url(/images/email.png?embed); }
/* Output:   */    .email { background: url(data:image/png;base64,NF8dG3I...); }

Precompile

# Rakefile
APP_FILE  = 'app.rb'
APP_CLASS = 'App'

# For Padrino users, do not forget to add your application namspace
# APP_CLASS = '<Project>::App'

require 'sinatra/assetpack/rake'

Invoking

Now you have the following tasks to precompile assets.

rake assetpack:precompile           # Precompile all assets
rake assetpack:precompile:files     # Precompile files only
rake assetpack:precompile:packages  # Precompile packages only

Settings

Assets block

All configuration happens in the assets block. You may invoke it in 2 ways:

class App < Sinatra::Base
  register Sinatra::AssetPack

  # Style 1
  assets do
    css :hello, [ '/css/*.css' ]
    css_compression :yui
  end

  # Style 2
  assets do |a|
    a.css :hello, ['/css/*.css' ]
    a.css_compression :yui
  end
end

Getting options

Invoking it without a block allows you to access the options. This works for almost all the options, with the exception for css, js and serve.

App.assets
App.assets.css_compression   #=> :yui

assets.serve

Serves files from LOCALPATH in the URI path PATH. Both parameters are required.

# Usage
serve 'PATH', :from => 'LOCALPATH'

Example

This makes /app/javascripts/vendor/jquery.js available as http://localhost:4567/js/vendor/jquery.js.

serve '/js', from: '/app/javascripts'

assets.js_compression
assets.css_compression

Sets the compression engine to use for JavaScript or CSS. This defaults to :jsmin and :simple, respectively.

If OPTIONS_HASH is given as a hash, it sets options for the engine to use.

# Usage:
assets {
  js_compression :ENGINE
  js_compression :ENGINE, OPTIONS_HASH
  css_compression :ENGINE
  css_compression :ENGINE, OPTIONS_HASH
}

Examples

Yo seriously check this out: the first line uses Sqwish with it's defaults, and the second line uses Sqwish with it's magic.

assets {
  css_compression :sqwish
  css_compression :sqwish, :strict => true
}

assets.js_compression_options
assets.css_compression_options

Sets the options for the compression engine to use. This is usually not needed as you can already set options using js_compression and css_compression.

# Usage:
assets {
  js_compression_options HASH
  css_compression_options HASH
}

Example

This sets the option for :munge for the CSS compression engine.

css_compression_options :munge => true

assets.css
assets.js

Adds packages to be used.

The NAME is a symbol defines the ID for that given package that you can use for the helpers. That is, If a CSS package was defined as css :main, [ ... ], then you will need to use <%= css :main %> to render it in views.

the URI is a string that defines where the compressed version will be served. It is optional. If not provided, it will default to "/assets/name.type" (eg: /assets/main.css).

the PATHs is an array that defines files that will be served. Take note that this is an array of URI paths, not local paths.

If a PATH contains wildcards, it will be expanded in alphabetical order. Redundancies will be taken care of.

# Usage:
assets {
  css :NAME, [ PATH1, PATH2, ... ]
  css :NAME, 'URI', [ PATH1, PATH2, ... ]
  js :NAME, [ PATH1, PATH2, ... ]
  js :NAME, 'URI', [ PATH1, PATH2, ... ]
}

Example

In this example, JavaScript files will be served compressed as /js/application.js (default since no URI is given). The files will be taken from ./app/javascripts/vendor/jquery*.js.

class App < Sinatra::Base
  assets {
    serve '/js', from: '/app/javascripts'
    js :application, [
      '/js/vendor/jquery.*.js',
      '/js/vendor/jquery.js'
    ]
  }
end

# In views: <%= js :application %>

assets.ignore

Excludes any URL paths that match the given spec.

These files will not show up in packages, and they will not be accessible.

By default, .* and _* are ignored. The former protects folders such as .svn from being accessed, and the latter protects Sass partial files from being accessed directly.

Note that this matches against URL paths, not local file paths. This means something like *.scss will not work, as all stylesheet files will be compiled to .css.

# Usage:
assets {
  ignore FILESPEC
}

Example

Here's an example.

class App < Sinatra::Base
  assets {
    # Ignores all files matching *.private.js in any folder.
    ignore '*.private.js'

    # Ignores all files in `/app/js/foo/**/*`
    ignore '/js/foo'
  }
end

Advanced usage

By default, .* and _* are ignored. To disable this behavior, you can use clear_ignores! before your ignore lines.

assets {
  clear_ignores!
  ignore '*.private.js'
}

To check if a certain file is ignored, use assets.ignore?

assets.ignored?("/css/_chrome.css")   #=> true

assets.prebuild

Caches the built packages on application startup.

If this is not used, the packages will be minified when they are first requested. This only has an effect in the production environment (or when Sinatra's reload_templates is otherwise set to false).

# Usage:
prebuild {true|false}

Example

In this example, the package for :application will be built when the application is started in the production environment.

class App < Sinatra::Base
  assets {
    js_compression :closure

    js :application, [
      '/js/vendor/jquery.*.js',
      '/js/vendor/jquery.js'
    ]
    prebuild true
  }
end

# $ RACK_ENV=production ruby app.rb
# ** Building /assets/application.js...
# == Sinatra/1.2.6 has taken the stage on 4567 for production
# >> Thin web server (v1.2.11 codename Bat-Shit Crazy)
# >> Maximum connections set to 1024
# >> Listening on 0.0.0.0:4567, CTRL+C to stop

assets.expires

Sets cache control headers for all assets handled by AssetPack. Defaults to expires 86400*30, :public. Passes the arguments to Sinatras #expires.

# Usage:
expires amount, *values

Example

In this example all assets get cached for a year.

class App < Sinatra::Base
  assets {
    js_compression :closure

    js :application, [
      '/js/vendor/jquery.*.js',
      '/js/vendor/jquery.js'
    ]
    expires 86400*365, :public
  }
end

assets.cache_dynamic_assets

Caches dynamic files unless they have been modified.

Useful during development if asset compilation of all dynamic assets on each request is slow. If set to true, dynamic assets will be compiled on the initial asset request, but only be re-compiled when the asset's mtime changes.

# Usage:
cache_dynamic_assets {true|false}

Example

In this example, all dynamic files will be compiled on first request, but later requests will be served from a cache unless the file is modified

class App < Sinatra::Base
  assets {
    js_compression :closure

    js :application, [
      '/js/vendor/jquery.*.js',
      '/js/vendor/jquery.js'
    ]
    cache_dynamic_assets true
  }
end

assets.asset_hosts

Adds asset hosts to be used in production.

Useful for hosting your assets on CDNs.

# Usage:
assets {
  asset_hosts ['URL1', 'URL2']
}

Example

In this example, all assets are served from multiple CDN subdomains:

class App < Sinatra::Base
  assets {
    serve '/css',     :from => 'app/css'
    serve '/js',      :from => 'app/js'

    asset_hosts [
      '//cdn-0.example.org',
      '//cdn-1.example.org'
    ]

    css :a, ["/css/style.css"]
    js :b, ["/js/hello.js"]
  }
end

Helpers

These are helpers you can use in your views.

<%= css %>

Shows a CSS package named PACKAGE. If OPTIONS_HASH is given, they will we passed onto the <link> tag to be generated as attributes.

You may specify as many packages as you need, as shown in the second usage line.

# Usage:
<%= css :PACKAGE %>
<%= css :PACKAGE_1, :PACKAGE_2, ...  :PACKAGE_N, OPTIONS_HASH %>
<%= css :PACKAGE, OPTIONS_HASH %>

Example 1

This links to the main stylesheet for screen media.

<%= css :main, media: 'screen' %>

<!-- Output: -->
<link rel='stylesheet' type='text/css' href='/css/main.873984.css' media='screen' />

Example 2

You may also invoke it with multiple packages.

<%= css :base, :app, :main, media: 'screen' %>

<!-- Output: -->
<link rel='stylesheet' type='text/css' href='/css/base.873984.css' media='screen' />
<link rel='stylesheet' type='text/css' href='/css/app.873984.css' media='screen' />
<link rel='stylesheet' type='text/css' href='/css/main.873984.css' media='screen' />

<%= js %>

Same as css, but obviously for JavaScript. You may also specify as many packages as you need, just with css.

# Usage:
<%= js :PACKAGE %>
<%= js :PACKAGE_1, :PACKAGE_2, ...  :PACKAGE_N, OPTIONS_HASH %>
<%= js :PACKAGE, OPTIONS_HASH %>

Example

This example embeds the main package with an ID.

<%= js :main, id: 'main_script' %>

<!-- Output: -->
<script type='text/javascript' src='/js/main.783439.js' id='main_script'></script>

<%= img %>

Shows an <img> tag from the given SRC. If the images is found in the asset directories (and ImageMagick is available), width and height attributes will be added.

# Usage:
img 'SRC'
img 'SRC', OPTIONS_HASH

If OPTIONS_HASH is given, they will we passed onto the <img> tag to be generated as attributes.

Example

This example renders an image with an alt tag.

<%= img '/images/icon.png', alt: 'Icon' %>

<!-- Output: -->
<img src='/images/icon.834782.png' width='24' height='24' alt='Icon' />`

Compass

AssetPack doesn't have built-in Compass support, but you can include it easily with Sinatra Support.

See also the Compass example application.

Contributing

See CONTRIBUTING.md for details on contributing and running test.

Acknowledgements

Β© 2011-2013, Rico Sta. Cruz. Released under the MIT License.

Sinatra-AssetPack is authored by Rico Sta. Cruz with help from it's contributors. It is sponsored by Sinefunc, Inc.

Sinatra-AssetPack is maintained by Jean-Philipe Doyle at Hookt Studios.

Github : @rstacruz, @j15e

Twitter : @rstacruz, @j15e

More Repositories

1

nprogress

For slim progress bars like on YouTube, Medium, etc
JavaScript
25,552
star
2

cheatsheets

My cheatsheets
SCSS
13,391
star
3

jquery.transit

Super-smooth CSS3 transformations and transitions for jQuery
JavaScript
7,328
star
4

rscss

Reasonable System for CSS Stylesheet Structure
3,894
star
5

flatdoc

Build sites fast from Markdown
CSS
2,679
star
6

webpack-tricks

Tips and tricks in using Webpack
2,359
star
7

sparkup

A parser for a condensed HTML format
Python
1,562
star
8

backbone-patterns

Common Backbone.js usage patterns.
760
star
9

remount

Mount React components to the DOM using custom elements
JavaScript
675
star
10

jsdom-global

Enable DOM in Node.js
JavaScript
472
star
11

hicat

Command-line syntax highlighter
JavaScript
405
star
12

kingraph

Plots family trees using JavaScript and Graphviz
JavaScript
390
star
13

vim-closer

Closes brackets
Vim Script
329
star
14

scour

Traverse objects and arrays with ease
JavaScript
308
star
15

mocha-jsdom

Simple jsdom integration with mocha
JavaScript
254
star
16

css-condense

[unsupported] A CSS compressor that shows no mercy
JavaScript
206
star
17

swipeshow

The unassuming touch-enabled JavaScript slideshow
JavaScript
191
star
18

rsjs

Reasonable System for JavaScript Structure
181
star
19

vim-coc-settings

My Vim settings for setting it up like an IDE
Vim Script
164
star
20

startup-name-generator

Let's name your silly startup
JavaScript
164
star
21

onmount

Safe, reliable, idempotent and testable behaviors for DOM nodes
JavaScript
156
star
22

psdinfo

Inspect PSD files from the command line
JavaScript
147
star
23

vim-hyperstyle

Write CSS faster
Python
144
star
24

vim-from-scratch

Rico's guide for setting up Vim
144
star
25

js2coffee.py

JS to CoffeeScript compiler. [DEPRECATED]
Python
127
star
26

firefox-stealthfox

Firefox customization for stealth toolbars
CSS
122
star
27

mocha-clean

Clean up mocha stack traces
JavaScript
107
star
28

jquery-stuff

A collection of small jQuery trinkets
JavaScript
96
star
29

npm-pipeline-rails

Use npm as part of your Rails asset pipeline
Ruby
95
star
30

navstack

Manages multiple screens with mobile-friendly transitions
JavaScript
94
star
31

bootstrap-practices

List of practices when using Bootstrap in projects
90
star
32

details-polyfill

Polyfill for the HTML5 <details> element, no dependencies
JavaScript
89
star
33

dom101

DOM manipulation utilities
JavaScript
82
star
34

unorphan

Removes text orphans
JavaScript
81
star
35

expug

Pug templates for Elixir
Elixir
80
star
36

stylelint-rscss

Validate CSS with RSCSS conventions
JavaScript
74
star
37

feh-blur-wallpaper

Blur your desktop wallpaper when windows are open
Shell
73
star
38

pomo.js

Command-line timer, great for Pomodoros
JavaScript
73
star
39

sinatra-backbone

Neat Backbone.js integration with Sinatra.
Ruby
72
star
40

flowloop

A Pomodoro-like timer for hyper-productivity
JavaScript
71
star
41

vimfiles

My VIM config files.
Lua
63
star
42

bookmarks

My bookmarks
63
star
43

my_qmk_keymaps

Keymaps for keyboards
C
59
star
44

typish

Typewriter simulator
JavaScript
58
star
45

iconfonts

Fine-tuned icon fonts integration for Sass, Less and Stylus
CSS
54
star
46

pre.js

Efficient, resilient resource preloader for JS/CSS
JavaScript
54
star
47

tape-watch

Rerun tape tests when files change
JavaScript
53
star
48

tinkerbin

Tinkerbin.com
JavaScript
52
star
49

vim-fastunite

Search for files fast
Vim Script
48
star
50

collaborative-etiquette

A manifesto for happy Open Source projects
46
star
51

decca

Render interfaces using pure functions and virtual DOM
JavaScript
45
star
52

vim-opinion

My opinionated vim defaults
Vim Script
44
star
53

modern-development

Using agile methods to build quality web applications
CSS
43
star
54

til-2013

Old version of http://ricostacruz.com/til (2015-2018)
CSS
42
star
55

ion

[deprecated] Ruby/Redis search engine.
Ruby
41
star
56

timetip

Deliciously-minimal time tracker for the command-line
JavaScript
40
star
57

vim-xtract

Extract the selection into a new file
Vim Script
39
star
58

bump-cli

Command-line version incrementer
JavaScript
39
star
59

halla

Native Slack wrapper app without the bloat
JavaScript
38
star
60

newsreader-sample-layout

CSS
36
star
61

ento

Simple, stateful, observable objects in JavaScript
JavaScript
36
star
62

cron-scheduler

Runs jobs in periodic intervals
JavaScript
35
star
63

promise-conditional

Use if-then-else in promise chains
JavaScript
34
star
64

ractive-touch

Touch events for Ractive
JavaScript
33
star
65

git-update-ghpages

Simple tool to update GitHub pages
Shell
33
star
66

jquery.unorphan

[deprecated] Obliterate text orphans.
JavaScript
33
star
67

greader

[UNSUPPORTED] Google Reader API client for Ruby
Ruby
32
star
68

penpad

Design and document web UI components
TypeScript
32
star
69

typecat

TypeScript
31
star
70

react-meta-elements

Sets document title and meta tags using React elements or hooks
TypeScript
31
star
71

vim-ultisnips-css

[deprecated] Write CSS in VIM faster.
Ruby
31
star
72

tape-plus

Nested tape tests with before/after, async, and promise support
JavaScript
30
star
73

taskpaper.js

Taskpaper parser in JavaScript
JavaScript
28
star
74

frontend-starter-kit

Rico's opinionated Metalsmith frontend kit
JavaScript
28
star
75

homebrew-backup

Back up your Homebrew profile
Shell
28
star
76

fishfiles

my fish-shell config files
Shell
28
star
77

passwordgen.js

Password generator for the command line
JavaScript
28
star
78

reacco

Generate documentation from README files.
Ruby
26
star
79

ghub

Open this project in github
Shell
26
star
80

sass_icon_fonts

Sass 3.2 integration with modern icon fonts.
CSS
26
star
81

lidoc

[Deprecated] Literate-programming style documentation tool.
CoffeeScript
24
star
82

rspec-repeat

Repeats an RSpec example until it succeeds.
Ruby
24
star
83

lofi

VHS music machine from the 80's
JavaScript
24
star
84

sinatra-template

Ruby
24
star
85

fish-asdf

Fish shell integrations for asdf version manager
Shell
24
star
86

wiki

Stuff
23
star
87

arch-installer

Install UI for Arch Linux
Shell
22
star
88

slack-emoji-magic

Magic: the Gathering emojis
Makefile
21
star
89

node-hledger

Node.js API for hledger
JavaScript
21
star
90

vimbower

Use bower, git and pathogen to manage your vim setup
21
star
91

ractive-promise-alt

Adaptor for Ractive.js to support promises
JavaScript
21
star
92

til-2020

Today I learned blog of @rstacruz
TypeScript
21
star
93

webpack-starter-kit

Baseline configuration for Webpack
JavaScript
21
star
94

phoenix_expug

Expug integration for Phoenix
JavaScript
20
star
95

cssutils

Collection of Sass utility mixins and other goodies.
CSS
20
star
96

responsive-modular-scale.css

Responsive typography using CSS variables
20
star
97

cdnjs-command

Command line helper for cdnjs.com
Ruby
20
star
98

curlformat

CLI utility to clean up your "Copy as cURL" strings
JavaScript
19
star
99

ractive-loader

ractive template loader for webpack
JavaScript
19
star
100

ajaxapi

Minimal AJAX library for APIs. Supports promises
JavaScript
18
star