The assets plugin adds support for rendering your CSS and javascript asset files on the fly in development, and compiling them to a single, compressed file in production.
This uses the render plugin for rendering the assets, and the render plugin uses tilt internally, so you can use any template engine supported by tilt for your assets. Tilt ships with support for the following asset template engines, assuming the necessary libraries are installed:
| css |
Less, Sass, Scss |
| js |
CoffeeScript |
You can also use opal as a javascript template engine, assuming it is installed.
Usage
When loading the plugin, use the :css and :js options to set the source file(s) to use for CSS and javascript assets:
plugin :assets, css: 'some_file.scss', js: 'some_file.coffee'
This will look for the following files:
assets/css/some_file.scss assets/js/some_file.coffee
The values for the :css and :js options can be arrays to load multiple files. If you want to change the paths where asset files are stored, see the Options section below.
Serving
In your routes, call the r.assets method to add a route to your assets, which will make your app serve the rendered assets:
route do |r| r.assets end
You should generally call r.assets inside the route block itself, and not under any branches of the routing tree.
Views
In your layout view, use the assets method to add links to your CSS and javascript assets:
<%= assets(:css) %> <%= assets(:js) %>
You can add attributes to the tags by using an options hash:
<%= assets(:css, media: 'print') %>
The assets method will respect the application’s :add_script_name option, if it is set it will automatically prefix the path with the SCRIPT_NAME for the request.
Asset Paths
If you just want the paths rather than the full tags, you can use assets_paths instead. This will return an array of the sources that the assets function would have put into tags:
assets_paths(:css) # => ["/assets/css/foo.css", "/assets/css/app.css"]
If compilation is turned on, it will return the path to the compiled asset:
assets_paths(:css) # => ["/assets/app.5e7b06baa1a514d8473b0eca514b806c201073b9.css"]
Asset Groups
The asset plugin supports groups for the cases where you have different css/js files for your front end and back end. To use asset groups, you pass a hash for the :css and/or :js options:
plugin :assets, css: {frontend: 'some_frontend_file.scss', backend: 'some_backend_file.scss'}
This expects the following directory structure for your assets:
assets/css/frontend/some_frontend_file.scss assets/css/backend/some_backend_file.scss
If you do not want to force that directory structure when using asset groups, you can use the group_subdirs: false option.
In your view code use an array argument in your call to assets:
<%= assets([:css, :frontend]) %>
Nesting
Asset groups also support nesting. You can use a nested hash when loading the plugin:
plugin :assets, css: {frontend: {dashboard: 'some_frontend_file.scss'}}
and an extra entry per nesting level when creating the tags.
<%= assets([:css, :frontend, :dashboard]) %>
Caching
The assets plugin uses the caching plugin internally, and will set the Last-Modified header to the modified timestamp of the asset source file when rendering the asset.
If you have assets that include other asset files, such as using @import in a sass file, you need to specify the dependencies for your assets so that the assets plugin will correctly pick up changes. You can do this using the :dependencies option to the plugin, which takes a hash where the keys are paths to asset files, and values are arrays of paths to dependencies of those asset files:
app.plugin :assets, dependencies: {'assets/css/bootstrap.scss'=>Dir['assets/css/bootstrap/' '**/*.scss']}
Asset Compilation
In production, you are generally going to want to compile your assets into a single file, with you can do by calling compile_assets after loading the plugin:
plugin :assets, css: 'some_file.scss', js: 'some_file.coffee' compile_assets
After calling compile_assets, calls to assets in your views will default to a using a single link each to your CSS and javascript compiled asset files. By default the compiled files are written to the public directory, so that they can be served by the webserver.
Asset Compression
You can use the :css_compressor and :js_compressor options to specify a compressor callable. The callable will be called with the uncompressed source, and should return the compressed source.
It is also possible to use the built-in compression options in the CSS or JS compiler, assuming the compiler supports such options. For example, with sass/sassc, you can use:
plugin :assets, css_opts: {style: :compressed}
Here are examples you can use for a few compressor libraries:
yui
require 'yuicompressor' plugin :assets, css_compressor: lambda{|v| ::YUICompressor.compress_css(v, munge: true) }, js_compressor: lambda{|v| ::YUICompressor.compress_js(v, munge: true) }
closure-compiler
require 'closure-compiler' plugin :assets, js_compressor: ::Closure::Compiler.new.method(:compile)
uglifier
require 'uglifier' plugin :assets, js_compressor: Uglifier.method(:compile)
minjs
require 'minjs' plugin :assets, js_compressor: proc { |content| Minjs::Compressor::Compressor.new(debug: false).compress(content).to_js }
Source Maps (CSS)
The assets plugin does not have direct support for source maps, so it is recommended you use embedded source maps if supported by the CSS compiler. For sass/sassc, you can use:
plugin :assets, css_opts: {:source_map_embed=>true, source_map_contents: true, source_map_file: "."}
With Asset Groups
When using asset groups, a separate compiled file will be produced per asset group.
Unique Asset Names
When compiling assets, a unique name is given to each asset file, using the a SHA1 hash of the content of the file. This is done so that clients do not attempt to use cached versions of the assets if the asset has changed.
Serving
When compiling assets, r.assets will serve the compiled asset files. However, it is recommended to have the main webserver (e.g. nginx) serve the compiled files, instead of relying on the application.
Assuming you are using compiled assets in production mode that are served by the webserver, you can remove the serving of them by the application:
route do |r| r.assets unless ENV['RACK_ENV'] == 'production' end
If you do have the application serve the compiled assets, it will use the Last-Modified header to make sure that clients do not redownload compiled assets that haven’t changed.
Asset Precompilation
If you want to precompile your assets, so they do not need to be compiled every time you boot the application, you can provide a :precompiled option when loading the plugin. The value of this option should be the filename where the compiled asset metadata is stored.
If the compiled asset metadata file does not exist when the assets plugin is loaded, the plugin will run in non-compiled mode. However, when you call compile_assets, it will write the compiled asset metadata file after compiling the assets.
If the compiled asset metadata file already exists when the assets plugin is loaded, the plugin will read the file to get the compiled asset metadata, and it will run in compiled mode, assuming that the compiled asset files already exist.
On Heroku
Heroku supports precompiling the assets when using Roda. You just need to add an assets:precompile task, such as:
namespace :assets do desc "Precompile the assets" task :precompile do require './app' App.compile_assets end end
Postprocessing
If you pass a callable object to the :postprocessor option, it will be called before an asset is served. If the assets are to be compiled, the object will be called at compilation time.
It is passed three arguments; the name of the asset file, the type of the asset file (which is a symbol, either :css or :js), and the asset contents.
It should return the new content for the asset.
You can use this to call Autoprefixer on your CSS:
plugin :assets, { css: [ 'style.scss' ], postprocessor: lambda do |file, type, content| type == :css ? AutoprefixerRails.process(content).css : content end }
External Assets/Assets from Gems
The assets plugin only supports loading assets files underneath the assets path. You cannot pass an absolute path to an asset file and have it work. If you would like to reference asset files that are outside the assets path, you have the following options:
-
Copy, hard link, or symlink the external assets files into the assets path.
-
Use indirection, such as an erb template that loads the external asset file, so that a file inside the assets path can reference files outside the assets path.
Plugin Keyword Arguments
add_suffix |
Whether to append a .css or .js extension to asset routes in non-compiled mode (default: false) |
compiled_asset_host |
The asset host to use for compiled assets. Should include the protocol as well as the host (e.g. “cdn.example.com”, “//cdn.example.com”) |
compiled_css_dir |
Directory name in which to store the compiled css file, inside :compiled_path (default: nil) |
compiled_css_route |
Route under :prefix for compiled css assets (default: :compiled_css_dir) |
compiled_js_dir |
Directory name in which to store the compiled javascript file, inside :compiled_path (default: nil) |
compiled_js_route |
Route under :prefix for compiled javscript assets (default: :compiled_js_dir) |
compiled_name |
Compiled file name prefix (default: ‘app’) |
compiled_path |
|
css |
The files contain the CSS assets, or a hash to use asset groups. |
css_compressor |
Compressor callable to use for compressing CSS |
css_dir |
Directory name containing your css source, inside :path (default: ‘css’) |
css_headers |
A hash of additional headers for your rendered css files |
css_opts |
Template options to pass to the render plugin (via :template_opts) when rendering css assets |
css_route |
Route under :prefix for css assets (default: :css_dir) |
dependencies |
A hash of dependencies for your asset files. Keys should be paths to asset files, values should be arrays of paths your asset files depends on. This is used to detect changes in your asset files. |
| early_hints |
Automatically send early hints for all assets. Requires the early_hints plugin. |
group_subdirs |
Whether a hash used in :css and :js options requires the assets for the related group are contained in a subdirectory with the same name (default: true) |
gzip |
Store gzipped compiled assets files, and serve those to clients who accept gzip encoding. |
headers |
A hash of additional headers for both js and css rendered files |
js |
The files contain the javascript assets, or a hash to use assets groups. |
js_compressor |
Compressor callable to use for compressing javascript |
js_dir |
Directory name containing your javascript source, inside :path (default: ‘js’) |
js_headers |
A hash of additional headers for your rendered javascript files |
js_opts |
Template options to pass to the render plugin (via :template_opts) when rendering javascript assets |
js_route |
Route under :prefix for javascript assets (default: :js_dir) |
path |
|
paths will be considered relative to the application's :root option.
postprocessor |
A block which should accept three arguments (asset name, asset type, content). This block can be used to hook into the asset system and make your own modifications before the asset is served. If the asset is to be compiled, the block is called at compile time. |
prefix |
Prefix for assets path in your URL/routes (default: ‘assets’) |
precompiled |
|
public |
|
relative_paths |
Use relative paths instead of absolute paths when setting up link and script tags for assets. |
sri |
Enables subresource integrity when setting up references to compiled assets. The value should be :sha256, :sha384, or :sha512 depending on which hash algorithm you want to use. This changes the hash algorithm that |
timestamp_paths |
Include the timestamp of assets in asset paths in non-compiled mode. Doing this can slow down development requests due to additional requests to get last modified times, but it will make sure the paths change in development when there are modifications, which can fix issues when using a caching proxy in non-compiled mode. This can also be specified as a string to use that string to separate the timestamp from the asset. By default, |
Classes and Modules
Constants
| CompressorNotFound | = | Class.new(RodaError) |
Internal exception raised when a compressor cannot be found |
|
| Config | = | Struct.new(*PLUGIN_ARGUMENTS, :compiled, :compiled_css_path, :compiled_css_prefix, :compiled_css_suffix, :compiled_js_path, :compiled_js_prefix, :compiled_js_suffix, :css_path, :css_prefix, :css_suffix, :expanded_dependencies, :js_path, :js_prefix, :js_suffix, :orig_opts) | ||
| DEFAULTS | = | { :compiled_name => 'app'.freeze, :js_dir => 'js'.freeze, :css_dir => 'css'.freeze, :prefix => 'assets'.freeze, :concat_only => false, :compiled => false, :add_suffix => false, :early_hints => false, :timestamp_paths => false, :group_subdirs => true, :compiled_css_dir => nil, :compiled_js_dir => nil, :sri => :sha256 }.freeze |
Public Class methods
Setup the options for the plugin. See the Assets module RDoc for a description of the supported options.
# File lib/roda/plugins/assets.rb 386 def self.configure(app, opts=OPTS) 387 RodaPlugins.check_supported_opts("the assets plugin", opts, PLUGIN_ARGUMENTS) 388 389 if app.assets_opts 390 prev_opts = app.assets_opts[:orig_opts] 391 orig_opts = prev_opts.merge(opts) 392 [:headers, :css_headers, :js_headers, :css_opts, :js_opts, :dependencies].each do |s| 393 if prev_opts[s] 394 if opts[s] 395 orig_opts[s] = prev_opts[s].merge(opts[s]) 396 else 397 orig_opts[s] = prev_opts[s].dup 398 end 399 end 400 end 401 app.opts[:assets] = orig_opts.dup 402 app.opts[:assets][:orig_opts] = orig_opts 403 else 404 app.opts[:assets] = opts.dup 405 app.opts[:assets][:orig_opts] = opts 406 end 407 opts = app.assets_opts 408 opts[:path] = app.expand_path(opts[:path]||"assets").freeze 409 opts[:public] = app.expand_path(opts[:public]||"public").freeze 410 411 # Combine multiple values into a path, ignoring trailing slashes 412 j = lambda do |*v| 413 opts.values_at(*v). 414 reject{|s| s.to_s.empty?}. 415 map{|s| s.chomp('/')}. 416 join('/').freeze 417 end 418 419 # Same as j, but add a trailing slash if not empty 420 sj = lambda do |*v| 421 s = j.call(*v) 422 s.empty? ? s : (s + '/').freeze 423 end 424 425 if opts[:precompiled] && !opts[:compiled] && ::File.exist?(opts[:precompiled]) 426 opts[:compiled] = app.send(:_precompiled_asset_metadata, opts[:precompiled]) 427 end 428 429 if opts[:timestamp_paths] && !opts[:timestamp_paths].is_a?(String) 430 opts[:timestamp_paths] = '/' 431 end 432 433 { 434 :compiled_name => 'app'.freeze, 435 :js_dir => 'js'.freeze, 436 :css_dir => 'css'.freeze, 437 :prefix => 'assets'.freeze, 438 :concat_only => false, 439 :compiled => false, 440 :add_suffix => false, 441 :early_hints => false, 442 :timestamp_paths => false, 443 :group_subdirs => true, 444 :compiled_css_dir => nil, 445 :compiled_js_dir => nil, 446 :sri => :sha256 447 }.each do |k, v| 448 opts[k] = v unless opts.has_key?(k) 449 end 450 451 [ 452 [:compiled_path, :prefix], 453 [:js_route, :js_dir], 454 [:css_route, :css_dir], 455 [:compiled_js_route, :compiled_js_dir], 456 [:compiled_css_route, :compiled_css_dir] 457 ].each do |k, v| 458 opts[k] = opts[v] unless opts.has_key?(k) 459 end 460 461 [:css_headers, :js_headers, :css_opts, :js_opts, :dependencies].each do |s| 462 opts[s] ||= {} 463 end 464 465 expanded_deps = opts[:expanded_dependencies] = {} 466 opts[:dependencies].each do |file, deps| 467 expanded_deps[File.expand_path(file)] = Array(deps) 468 end 469 470 if headers = opts[:headers] 471 opts[:css_headers] = headers.merge(opts[:css_headers]) 472 opts[:js_headers] = headers.merge(opts[:js_headers]) 473 end 474 opts[:css_headers][RodaResponseHeaders::CONTENT_TYPE] ||= "text/css; charset=UTF-8".freeze 475 opts[:js_headers][RodaResponseHeaders::CONTENT_TYPE] ||= "application/javascript; charset=UTF-8".freeze 476 477 [:css_headers, :js_headers, :css_opts, :js_opts, :dependencies, :expanded_dependencies].each do |s| 478 opts[s].freeze 479 end 480 [:headers, :css, :js].each do |s| 481 opts[s].freeze if opts[s] 482 end 483 484 # Used for reading/writing files 485 opts[:js_path] = sj.call(:path, :js_dir) 486 opts[:css_path] = sj.call(:path, :css_dir) 487 opts[:compiled_js_path] = j.call(:public, :compiled_path, :compiled_js_dir, :compiled_name) 488 opts[:compiled_css_path] = j.call(:public, :compiled_path, :compiled_css_dir, :compiled_name) 489 490 # Used for URLs/routes 491 opts[:js_prefix] = sj.call(:prefix, :js_route) 492 opts[:css_prefix] = sj.call(:prefix, :css_route) 493 opts[:compiled_js_prefix] = j.call(:prefix, :compiled_js_route, :compiled_name) 494 opts[:compiled_css_prefix] = j.call(:prefix, :compiled_css_route, :compiled_name) 495 opts[:js_suffix] = (opts[:add_suffix] ? '.js' : '').freeze 496 opts[:css_suffix] = (opts[:add_suffix] ? '.css' : '').freeze 497 498 unless opts[:concat_only] 499 [:css_compressor, :js_compressor].each do |s| 500 case v = opts[s] 501 when nil, :none, Proc, Method 502 nil 503 else 504 RodaPlugins.warn "Support for the assets plugin #{s}: #{v.inspect} option will be removed in Roda 4. See the assets plugin documentation for how to use an appropriate proc or method." 505 end 506 end 507 end 508 509 opts.freeze 510 app.opts[:assets_config] = Config.new(*opts.values_at(*Config.members)).freeze 511 end
Load the render, caching, and h plugins, since the assets plugin depends on them.
# File lib/roda/plugins/assets.rb 368 def self.load_dependencies(app, opts = OPTS) 369 app.plugin :_json 370 app.plugin :_add_script_name 371 app.plugin :render 372 app.plugin :caching 373 app.plugin :h 374 375 if opts[:relative_paths] 376 app.plugin :relative_path 377 end 378 379 if opts[:early_hints] 380 app.plugin :early_hints 381 end 382 end