Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include Assets Only If They Exist

In our current rails app, we are following certain patterns for including assets such as scripts and stylesheets.

For instance, one such pattern is (code inside the layout):

= stylesheet_link_tag controller.controller_name

The problem here is that not all of the controllers are going to have associated stylesheets. What is the best way to check if an asset exists? Specifically, I know there is some trickery here due to the cache busting asset names.

like image 561
ghempton Avatar asked Nov 21 '11 02:11

ghempton


2 Answers

Finally figured this one out. Asset existence can be checked as follows:

YourApp::Application.assets.find_asset("#{asset}.css").nil?

The answer would then be:

= stylesheet_link_tag controller.controller_name if YourApp::Application.assets.find_asset("#{controller.controller_name}.css")
like image 172
ghempton Avatar answered Sep 22 '22 01:09

ghempton


I had found this answer before and we'd been happily using find_asset in our application (Rails 3.2.16), until one day it started bombing out.

After some digging, it turns out that even in a production environment, with asset precompilation enabled, the first call to find_asset will attempt to actually compile the asset it's looking for, even if that asset has been precompiled already. As you can imagine, this is not good news -- in our specific case, we were pulling in a Compass library file into a stylesheet, which worked in dev and during precompile, but not in production, where Compass was not in the assets load path.

Long story short, find_asset is not a bulletproof way to determine if an asset is available to include. You can read a bunch more about it in the issue someone tried to file about this, and which was subsequently closed as not a bug: https://github.com/sstephenson/sprockets/issues/411

The real way to determine if an asset exists, and which works in both compile and precompile modes is demonstrated in the hoops that the filer of the above issues needed to jump through. Here's the diff for his fix: https://github.com/fphilipe/premailer-rails/pull/55/files

I'm putting this here in hopes that other Googlers who find this don't fall into the same trap I did!

like image 34
rusty Avatar answered Sep 24 '22 01:09

rusty