Created
June 2, 2016 09:16
-
-
Save AdrienGiboire/edfdb897d790a36a2c8ead268bb230d8 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
task 'assets:precompile:before' do | |
require 'uglifier' | |
require 'sprockets' | |
require 'term/ansicolor' | |
include Term::ANSIColor | |
unless %w{production}.include? Rails.env | |
print yellow(bold("rake assets:precompile should only be run in RAILS_ENV=production, you are risking unminified assets")), "\n" | |
end | |
# Ensure we ALWAYS do a clean build | |
# .erbs can get out of date quickly, especially with plugins | |
print bold("--- Purging temp files"), "\n" | |
`rm -fr #{Rails.root}/tmp/cache` | |
print bold("--- Bundling assets"), "\n" | |
end | |
def assets_path | |
"#{Rails.root}/public/assets" | |
end | |
def compress(from,to) | |
data = File.read("#{assets_path}/#{from}") | |
uglified, map = Uglifier.new(comments: :none, | |
screw_ie8: true, | |
source_filename: File.basename(from), | |
output_filename: File.basename(to) | |
) | |
.compile_with_map(data) | |
dest = "#{assets_path}/#{to}" | |
print bold("DEBUG -- : Writing Source Map for #{to}"), "\n" | |
File.write(dest, uglified << "\n//# sourceMappingURL=#{"/assets/#{to}.map"}") | |
print bold("DEBUG -- : Source Map for #{to} #{dest + ".map"}"), "\n" | |
File.write(dest + ".map", map) | |
end | |
def gzip(path) | |
print "gzip #{path}", "\n" | |
print `gzip -f -c -7 #{path} > #{path}.gz`, "\n" | |
end | |
def concurrent? | |
if ENV["CONCURRENT"] == "1" | |
concurrent_compressors = [] | |
yield(Proc.new { |&block| concurrent_compressors << Concurrent::Future.execute { block.call } }) | |
concurrent_compressors.each(&:wait!) | |
else | |
yield(Proc.new { |&block| block.call }) | |
end | |
end | |
task 'assets:precompile' => 'assets:precompile:before' do | |
manifest = Sprockets::Manifest.new(assets_path) | |
concurrent? do |proc| | |
manifest.files | |
.select{|k,v| k =~ /\.js$/} | |
.each do |file, info| | |
path = "#{assets_path}/#{file}" | |
_file = (d = File.dirname(file)) == "." ? "_#{file}" : "#{d}/_#{File.basename(file)}" | |
_path = "#{assets_path}/#{_file}" | |
if File.exists?(_path) | |
print yellow(bold("Skipping: #{file} already compressed")), "\n" | |
else | |
print yellow(bold("Compressing: #{file}")), "\n" | |
proc.call do | |
# We can specify some files to never minify | |
unless (ENV["DONT_MINIFY"] == "1") | |
FileUtils.mv(path, _path) | |
compress_ruby(_file,file) | |
end | |
info["size"] = File.size(path) | |
info["mtime"] = File.mtime(path).iso8601 | |
gzip(path) | |
end | |
end | |
end | |
end | |
manifest.send :save | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment