Add logic to your Rails asset pipeline manifests
2013-09-22
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:
=
=
<%
# ...
if Rails.env.development?
require_asset ()
else
require_asset ()
end
require_asset ()
# Include plugin javascripts
DiscoursePluginRegistry.javascripts.each do
require_asset(js)
end