Question

In a Rails 3.1 app, one controller needs to have all its views compile whatever Sass stylesheets they might need per request using a set of custom variables. Ideally, the compilation must happen via the asset pipeline so that content-based asset names (ones that include an MD5 hash of the content) are generated. It is important for the solution to use pure Sass capabilities as opposed to resorting to, for example, ERB processing of Sass stylesheets.

From the research I've done here and elsewhere, the following seems like a possible approach:

  1. Set up variable access

    • Create some type of variable accessor bridge using custom Sass functions, e.g., as described by Konstantin Haase here (gist). This seems pretty easy to do.

    • Configure all variable access via a Sass partial, e.g., in _base.sass which is the Compass way. The partial can use the custom functions defined above. Also easy.

  2. Capture all asset references

    • Decorate the asset_path method of the view object. I have this working well.

    • Resolve references using a custom subclass of Sprockets::Environment. This is also working well.

  3. Force asset recompilation, regardless of file modification times

    • I have not found a good solution for this yet.

    • I've seen examples of kicking off Sass processing manually by instantiating a new Sass::Engine and passing custom data that will be available in Sass::Script::Functions::EvaluationContext. The problem with this approach is that I'd have to manage file naming and paths myself and I'd always run the risk of possible deviation from what Sprockets does.

    • I wasn't able to find any examples of forcing Sprockets processing on a per-request basis, regardless of file mod times, that also allows for custom variable passing.

I'd appreciate comments on the general approach as well as any specific pointers/suggestions on how to best handle (3).

Was it helpful?

Solution

Sim.

It is possible. Look here SASS: Set variable at compile time

I wrote a solution to address it, I'll post soon and push it here, in case you or someone else still need it.

OTHER TIPS

SASS is designed to be pre-compiled to CSS. Having Sprockets do this for every request for a view on a per request basis is not going to perform very well. Every request is going to have to wait for the compilation to be done, and it is not fast (from a serving-pages point of view).

The MD5 generation is within Sprockets, so if you are changing custom variables you are going to have to force a compilation on every single request to make sure that changes are seen because the view is (probably) not going to know.

It sounds as though this is not really in the sweet-spot of the asset-pipeline, and you should look at doing something more optimised for truly dynamic CSS.

Sorry. :-)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top