September 22, 2013

Add logic to your Rails asset pipeline manifests

Recently, while reading Discourse’s source code, I learned that Rails asset pipeline Javascript/CSS manifests are just plain old JS/CSS files and can be passed through a templating engine. This means you can add the .erb extension to add logic. This is useful if you want to use a prod-only CDN, serve dev-only Javascript debug code, or in Discourse’s case, dynamically load plugin assets.

When including assets from Ruby code in your manifest, use Sprocket’s require_asset method (rubydoc).

From Discourse’s application.js.erb:

//= require ./env
//= require ./discourse/components/probes.js

# ...

if Rails.env.development?
  require_asset ("./external_development/ember.js")
  require_asset ("./external_production/ember.js")

require_asset ("./main_include.js")

# Include plugin javascripts
DiscoursePluginRegistry.javascripts.each do |js|
All content, unless otherwise noted, is licensed under a Creative Commons Attribution 4.0 International License.