Undo in assets:clobber What You Do in assets:precompile

As a best practice, when you enhance your Rails app’s assets:precompile task to build static assets that can be served faster than if they needed to be compiled at runtime, you should also enhance assets:clobber to remove the artifacts you create.

Rails built in precompile task will build assets by running CSS and JavaScript through preprocessors, combine them into a single file (or more, depending on setup), and give them file names with SHA sums.

The assets:clobber Rake task is the less well-known sibling of assets:precompile. It’s really useful when you want to be able to verify that your build process works correctly that you can also tear it down completely. This avoids running with precompiled assets in your development environment, for example. In the default case it deletes the files generated by assets:precompile.

Both of these tasks (and indeed any other Rake task) have additional tasks run either before or after their current behavior. To run before, you’d add

task "assets:clobber" => :my_teardown_task

to Rakefile while to run after you can write

Rake::Task["assets:precompile"].enhance(:my_setup_task)`

In my case, I enhanced assets:precompile to also convert the markdown + YAML front matter in the files that I use for writing blog posts using Frontmatter to HTML and metadata and cache the results into the database to be rendered directly into responses. Until recently I hadn’t also enhanced the complementary assets:clobber task to clear those generated HTML strings out. I was just deleting all articles from my database manually.

Adding this behavior to assets:clobber allows me to think through more fully what it is that I want to happen when I tear down my precompiled blog articles, and it gives me confidence that I can do it easily and consistently.

Adding additional behavior to assets:precompile is useful when you want to be able to augment your build step, especially since the Heroku Buildpack for Rails apps will run that task during deploys. Just remember to also add something to assets:clobber to undo whatever it is that you built as a quality of life improvement.