Last active
March 22, 2018 14:53
-
-
Save derekclee/459f2091e34bc38c9231 to your computer and use it in GitHub Desktop.
Compressing static svg files for the rails asset pipeline
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
# I used https://github.com/eliotsykes/rack-zippy to serve gzipped static assets. | |
# By default the rails asset pipeline was not compressing any static svg files, | |
# so I did the following to achive that. | |
# | |
# First create a rake task that will fine and compress svg files. | |
# File: lib/tasks/assets_svg_compress.rake | |
namespace :assets do | |
task :svg_compress => :environment do | |
svg_files = Dir["./public/**/*.svg"] | |
svg_files.each do |file| | |
puts "Compressing #{file}" | |
Zlib::GzipWriter.open("#{file}.gz") do |file_gz| | |
File.open(file) do |fp| | |
while chunk = fp.read(16*1024) do | |
file_gz.write chunk | |
end | |
end | |
file_gz.close | |
end | |
end | |
end | |
end | |
# Then enhance the normal `assets:precomiple` task by giving it another action. | |
# See http://ruby-doc.org/stdlib-2.2.0/libdoc/rake/rdoc/Rake/Task.html#method-i-enhance | |
# | |
# File: lib/tasks/assets_precompile.rake | |
Rake::Task['assets:precompile'].enhance do | |
Rake::Task['assets:svg_compress'].invoke | |
end | |
# Now rack-zippy will serve up compressed svg files. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment