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
@fleetio
Copy link
Author

fleetio commented Jul 3, 2012

Asset Exists?

Helper method that returns true if an asset exists in the Rails asset pipeline, false if not.

Useful for...

If you want to include page specific CSS based on the current controller, but your don't want to include a CSS link if the asset file doesn't exist for the current controller.

@gerwitz
Copy link

gerwitz commented Feb 11, 2014

Possibly more efficient: Rails.application.assets.find_asset(path).nil?

@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