Created
December 9, 2015 18:27
-
-
Save TooManyBees/769ca55343b8917396ec to your computer and use it in GitHub Desktop.
DumpAssetHelper - Ruby On Rails helper module to look up precompiled assets
This file contains 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
# Include this in ApplicationHelper, or another view helper module | |
module DumpAssetHelper | |
# Helper for inlining compiled assets | |
# `dump_asset("lib/like_button.js")` | |
# `dump_asset("components/avatar.css", :once)` | |
def dump_asset name, option=nil | |
unless option == :once && dumped_assets.include?(name) | |
dumped_assets << name | |
asset = find_asset(name) | |
if !Rails.env.production? | |
raise "No content for asset at #{name}" if asset.blank? | |
raise "Asset #{name} not added to precompile list" if !is_precompiled?(name) | |
end | |
asset | |
end | |
end | |
private | |
# Keeps track of what has been dumped for the current request (unique per instance) | |
def dumped_assets | |
@dumped ||= Set.new | |
end | |
# Cache of every precompiled asset that's looked up (unique per entire app process) | |
@@asset_cache = {} | |
ENVS_WITHOUT_PRECOMPILATION = ["development", "test"] | |
def find_asset name | |
if ENVS_WITHOUT_PRECOMPILATION.include?(Rails.env) | |
Rails.application.assets.find_asset(name).to_s | |
else | |
@@asset_cache[name] ||= begin | |
fingerprint = Rails.application.assets_manifest.assets[name] | |
return nil unless fingerprint | |
File.read(File.join(Rails.root, "public", "assets", fingerprint)).to_s.html_safe | |
rescue Errno::ENOENT => e | |
# Good place to surface an error about a missing precompiled asset | |
nil | |
end | |
end | |
end | |
def is_precompiled? name | |
Rails.application.config.assets.precompile.any? do |glob| | |
case glob | |
when String | |
File.fnmatch(glob, name) | |
when Regexp | |
name =~ glob | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment