Created
April 11, 2018 14:12
-
-
Save seanlinsley/ab0fb9fbc063e9812629be8cb6a92f2f to your computer and use it in GitHub Desktop.
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
# Sprockets no longer creates undigested assets, so we have to emulate the old behavior to keep vendored JS libraries happy. | |
# This automatically uses the newest asset in cases where the same file exists multiple times (like with Capistrano). | |
# | |
# https://github.com/rails/sprockets-rails/issues/49 | |
# | |
# digested: 4-star-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.jpg | |
# undigested: 4-star.jpg | |
assets_without_digest = -> do | |
digest = /(-{1}[a-z0-9]{64}*\.{1}){1}/ | |
assets = Dir.glob File.join Rails.root, 'public/assets/**/*' | |
assets.reject! do |file| | |
File.directory?(file) || file !~ digest || ['.json', '.map'].include?(File.extname(file)) | |
end | |
assets.group_by{ |file| file.gsub digest, '.' }.each do |undigested_file, files| | |
newest_file = files.max_by{ |file| File.ctime file } | |
FileUtils.cp newest_file, undigested_file | |
end | |
end | |
# Sprockets generates source maps, but it only tells browsers about their existence in local dev. | |
# This patch makes it so that statically compiled assets link their the source map. | |
# | |
# https://github.com/rails/sprockets/issues/502 | |
# | |
# Given an application.js.coffee source file, Sprockets generates these files: | |
# | |
# minified source: application-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.js | |
# source map: application.js-bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.map | |
# unminifed source: application.source-cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc.coffee | |
add_source_map_url = -> do | |
source_maps = Dir.glob File.join Rails.root, 'public/assets/*.map' | |
source_maps.each do |source_map| | |
/(?<name>\w+)\.(?<ext>\w+)-/ =~ source_map | |
Dir.glob(File.join(Rails.root, "public/assets/#{name}-*.#{ext}")).each do |served_file| | |
next if `tail -n 1 #{served_file}`.include? 'sourceMappingURL' | |
comment = case ext | |
when 'js' | |
"\n//# sourceMappingURL=#{File.basename(source_map)}" | |
when 'css' | |
"\n/*# sourceMappingURL=#{File.basename(source_map)} */" | |
end | |
file = File.open served_file, 'a' | |
file.write comment | |
file.close | |
end | |
end | |
end | |
task 'assets:precompile' => 'environment' do | |
assets_without_digest.call | |
add_source_map_url.call | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment