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 |
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
Possibly more efficient: Rails.application.assets.find_asset(path).nil?