ruby-on-rails-4asset-pipeline

Rails Asset Pipeline - How to determine if an asset exists?


Is there any way to ask the Asset Pipeline if an asset exists? The suggestions I largely see involve manually checking the file path with File.exist?. The problem with that is that I have several gems that include assets, so I would have to look at the assets directories for each of those, right? This seems like something I would expect to be baked into the Asset Pipeline, but I can't find any reference to it.

My current solution is an ugly hack, so I hope you have something better. Calling asset_path(file) will either return a new URL (/asset/xyz) for an asset or the same path if it does not exists (or if it's an absolute path). So my ugly hack is:

def has_asset?(path)
  # Asset pipeline only does relative paths
  if path[0] == '/'
    return false
  end
  asset_path(path) != '/#{path}'
end

Solution

  • I just found that I can use assets.find_asset:

    def has_asset?(path)
      Rails.application.assets.find_asset(path) != nil
    end