Rails CSS & JS with Asset Pipeline

sset pipeline compiles and compress all css and scss into a single file for quick downloads when loaded into production. It also compiles and compresses all of the js files as well.
Last night I was brutalized by the asset pipeline within Rails 3.2.7. I uploaded a new release of a website I’ve been working on only to get a 500 error with a non-descriptive message “Sorry, something went wrong.” I love error messages like that. Tells me exactly where to start looking in troubleshooting. Of course I had modified just about every file in the website, so where to start troubleshooting was the first challenge. There were no entries in the httpd logs and only one line in the app log that an error occurred on retrieving the very first page of the site.

After about 30 minutes of plunking around trying various things to get more descriptive messages to isolate the problem, I decided to revert the way I was calling the stylesheets and javascripts in the app/views/layouts. I had wanted to streamline the css and js files I was pulling down for each request and had changed it to only pull the global css file and the controller specific css file. As soon as I reverted the changes, bam – everything worked.

Asset pipeline in Rails compiles the css and scss files into a single compressed css file. Asset pipeline also does something similar for the javascript files. In development, the development web server does not compress the files, so all the individual files exist and get pulled correctly with my changes. In production since there is only a single file, in essence I was calling a non-existing file.

So how do I continue to have controller specific CSS settings and allow asset pipeline to do what it wants to do. One of the challenges in software development is keeping within the framework you are using so that you can more easily port to new framework versions. So I what I wanted to do was work with asset pipeline and keep the controller specific CSS settings.

I ended up adding a class to the tag in the main app layout. The class is named after the controller. In the scss files for each controller I make sure that all the css settings are under the corresponding body class. This ensure I don’t get a side effect from another controller’s specific css.

The ruby code I added to the application.html.erb layout is:

In each controller’s css file I added the class body.{controller} {}, where {contorller} is the actual controller name. I make sure all of the controller’s css setting are children of this class.

Then in development to clean up the Webrick development server, in Config/Environments/Development.rb I set config.assets.debug = false. This turned off all the asset loading messages.