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