Rails Asset Pipeline - How to determine if an asset exists?
The currently accepted answer does not work in production.
I use the following method to work in both development and production environments:
module AssetHelper
def asset_exists?(path)
if Rails.env.production?
Rails.application.assets_manifest.find_sources(path) != nil
else
Rails.application.assets.find_asset(path) != nil
end
end
end
I had problems with the suggested solutions above sometimes returning true when an asset did not exist this fixes the issue
def asset_exists?(path)
if Rails.env.production?
all_assets = Rails.application.assets_manifest.find_sources(path)
if all_assets
keys = Rails.application.assets_manifest.assets.keys
if keys.include?(path)
true
else
false
end
else
false
end
else
Rails.application.assets.find_asset(path) != nil
end
end
I just found that I can use assets.find_asset
:
def has_asset?(path)
Rails.application.assets.find_asset(path) != nil
end