Blog · Articles tagged with "sprockets" · show all articles »

How to compile custom Sass stylesheets dynamically during runtime

Update January 15 2016: As someone pointed out in a comment on the gist, this method doesn't seem to work anymore with recent versions of Sprockets.

Update May 29 2013: The name of the stylesheet files was changed slightly (hyphen replaced by underscore) after feedback in the comments.

In any Rails 3.1 (or newer) app where the user can change the style (e.g. layout, colors, dimensions) of certain items you come to the point where you wish you could use all of the sweetness of the Rails asset pipeline to generate custom stylesheets dynamically during runtime.

After a bit of googling I realized what it comes down to is imitating the process Rails performs when precompiling all assets on deploy, only that we want to want to compile Sass code that was generated dynamically, not read from a static file in app/assets/javascripts. After having a look at the assets:precompile Rake task which does the heavy lifting it's clear that Sprockets::StaticCompiler is the main suspect in this case.

Read on