Rails 3.1: Determine if asset exists

陌路散爱 提交于 2019-11-29 22:05:41
Joe Van Dyk

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

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.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

Tatiana Tyu

See this answer: https://stackoverflow.com/a/8217598/549252

= Rails.application.assets.find_asset("my_asset.css").nil?
rusty

Please see the answer here for a discussion on why find_asset may not always work:

Include Assets Only If They Exist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!