cssruby-on-rails-3assetsexecute

Ruby on Rails - Executing code on compile


I would like to use ruby code in a CSS file on compile and make it a static asset, and then potentially minify it afterwards. How can I do this?


Solution

  • The asset pipeline in Rails 3.1+ will send your assets through a series of pre-processors based on it's filename. For instance, if you have stylesheet.css.scss, the file is sent through the SASS processor to turn it into CSS.

    The fun begins when you chain extensions together, in order to send your asset through multiple processors. In your case, you can name your asset stylesheet.css.scss.erb to send it through ERB first, then SASS. Here's a small example of what that might look like:

    .some_class {
      background-image: url(<%= asset_path('image.png') %>);
      color: <%= some_ruby_code_to_generate_a_color %>;
    }
    

    So, as you would in a regular ERB view template, you can simply throw Ruby code between <%= %> tags into your asset which will be run when the asset is being compiled (or pre-compiled).

    With respect to minification, that's something that's simply handled by the asset pipeline through some config options. Check out the Rails guide for the asset pipeline for more details.