Skip to content

Instantly share code, notes, and snippets.

@fleetio
Created July 3, 2012 19:25
Show Gist options
  • Save fleetio/3042196 to your computer and use it in GitHub Desktop.
Save fleetio/3042196 to your computer and use it in GitHub Desktop.
Rails helper method that determines if an asset exists
- if asset_exists? "#{params[:controller]}.css"
= stylesheet_link_tag params[:controller]
- if asset_exists? "#{params[:controller]}.js"
= javascript_include_tag params[:controller]
# Returns true if an asset exists in the Asset Pipeline, false if not.
def asset_exists?(path)
begin
pathname = Rails.application.assets.resolve(path)
return !!pathname # double-bang turns String into boolean
rescue Sprockets::FileNotFound
return false
end
end
@odlp
Copy link

odlp commented Dec 22, 2016

With Rails 5 / Sprockets 3.7 this works too:

def asset_exists?(path)
  Rails.application.assets.resolve(path).present? 
end

The resolve method will return nil, whereas resolve! will throw an exception.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment