Created
July 3, 2012 19:25
-
-
Save fleetio/3042196 to your computer and use it in GitHub Desktop.
Rails helper method that determines if an asset exists
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- if asset_exists? "#{params[:controller]}.css" | |
= stylesheet_link_tag params[:controller] | |
- if asset_exists? "#{params[:controller]}.js" | |
= javascript_include_tag params[:controller] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
With Rails 5 / Sprockets 3.7 this works too:
The
resolve
method will return nil, whereasresolve!
will throw an exception.