Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3.1: Determine if asset exists

Is there a built-in way to determine if an asset exists without resorting to File.exists?(File.join(Rails.root, "foo", "bar", "baz")) and that looks through the asset paths.

My app goes and fetches images from a remote server on a Resque queue; until we have the image downloaded I want to serve a placeholder image. Currently I'm using File.exists... but this means hard-coding a path, which sucks, or looking through the configured asset paths. It seems like this should be there already, but I can't find it in the docs.

like image 683
Jim Zajkowski Avatar asked Jul 21 '11 21:07

Jim Zajkowski


2 Answers

Given an image in app/assets/images/lolshirts/theme/bg-header.png,

Rails.application.assets.find_asset 'lolshirts/theme/bg-header.png'  => #> Sprockets::StaticAsset:0x80c388ec pathname="/Users/joevandyk/projects/tanga/sites/lolshirts/app/assets/images/lolshirts/theme/bg-header.png", mtime=2011-10-07 12:34:48 -0700, digest="a63cc84aca38e2172ae25de3d837c71a">  Rails.application.assets.find_asset 'notthere.png'  => nil 
like image 53
Joe Van Dyk Avatar answered Sep 22 '22 15:09

Joe Van Dyk


Since this is still the top question when searching Google, and since the accepted answer does not work properly in production (at least in some cases), here is the solution that works for me (Rails 4.x to 6.x at least):

def asset_exist?(path)   if Rails.configuration.assets.compile     Rails.application.precompiled_assets.include? path   else     Rails.application.assets_manifest.assets[path].present?   end end 

This is copied from this github issue

like image 29
DannyB Avatar answered Sep 26 '22 15:09

DannyB