Rails 3.1: Asset Determination

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 which looks for resource paths.

My application sends and selects images from a remote server in the Resque queue; until we upload the image, I want to serve as a placeholder image. I am currently using File.exists ... but that means hard-coding a path that sucks or looks at configured asset paths. It seems like it should already be, but I can't find it in the docs.

+46
asset-pipeline
Jul 21 2018-11-21T00:
source share
4 answers

Given the 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 
+68
Oct 08 2018-11-11T00:
source share

Since this is still the main question when searching on Google, and since the accepted answer does not work properly in production (at least in some cases), here is a solution that works for me (Rails 4.2.5.1):

 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.

+29
Feb 10 '16 at 15:40
source share

See this answer: stack overflow

 = Rails.application.assets.find_asset("my_asset.css").nil? 
+7
Jun 24 2018-12-12T00:
source share

Please see the answer here to discuss why find_asset may not always work:

Include assets only if they exist

+2
Mar 21 '14 at 17:58
source share



All Articles