Skip to content

Instantly share code, notes, and snippets.

@TooManyBees
Created December 9, 2015 18:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TooManyBees/769ca55343b8917396ec to your computer and use it in GitHub Desktop.
Save TooManyBees/769ca55343b8917396ec to your computer and use it in GitHub Desktop.
DumpAssetHelper - Ruby On Rails helper module to look up precompiled assets
# 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