Skip to content

Instantly share code, notes, and snippets.

@derekclee
Last active March 22, 2018 14:53
Show Gist options
  • Save derekclee/459f2091e34bc38c9231 to your computer and use it in GitHub Desktop.
Save derekclee/459f2091e34bc38c9231 to your computer and use it in GitHub Desktop.
Compressing static svg files for the rails asset pipeline
# 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