Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 934
Jeremy Gillick Avatar asked Sep 13 '14 18:09

Jeremy Gillick


People also ask

How do you Precompile an asset?

To compile your assets locally, run the assets:precompile task locally on your app. Make sure to use the production environment so that the production version of your assets are generated. A public/assets directory will be created. Inside this directory you'll find a manifest.

How does rails asset pipeline work?

The asset pipeline provides a framework to concatenate and minify or compress JavaScript and CSS assets. It also adds the ability to write these assets in other languages such as CoffeeScript, Sass and ERB. Prior to Rails 3.1 these features were added through third-party Ruby libraries such as Jammit and Sprockets.

What does rake assets Precompile do?

rake assets:precompile. We use rake assets:precompile to precompile our assets before pushing code to production. This command precompiles assets and places them under the public/assets directory in our Rails application. Let's begin our journey by looking at the internals of the Rails Asset Pipeline.


1 Answers

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
like image 170
Greg Blass Avatar answered Oct 03 '22 21:10

Greg Blass