Check for Compiled Assets Existence.

Have you ever run into a situation where you wanted to check if an asset exists in Rails. Then when you deploy to production, it doesn’t work. That is because Rails by default compiles assets which changes the path and file name.

We found this out the hard way, luckily it was just the first deploy so
it didn’t affect any customers. So I thought I would share the solution we found.

Inside of a helper add the following code:

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

Then in your view or controller:

if asset_exist?('test.png')
  puts "Asset found!"
else
  puts "Asset not found!"
end

There you have it!