Skip to content

Instantly share code, notes, and snippets.

@amw amw/assets.rake
Last active Aug 29, 2015

Embed
What would you like to do?
Preparing compressed (gzipped) Rails assets for Nginx mod_gzip_static
# lib/tasks/assets.rake
namespace :assets do
ManifestPattern = /^manifest-[0-9a-f]{32}\.json$/
ExtensionsToCompress = %w{.js .css .json}.freeze
desc "GZip assets"
task :compress do
files = Pathname.glob(Rails.root.join('public/assets/**/*')).map do |file|
next unless file.extname.in? ExtensionsToCompress
next if file.basename.to_s =~ ManifestPattern
gzipped = file.to_s + ".gz"
next if File.exist? gzipped
[file, gzipped]
end.compact
start = -> item, index {
gzipped = item.last
puts "Creating #{gzipped}"
}
Parallel.each files, start: start do |file,gzipped|
Zlib::GzipWriter.open gzipped, Zlib::BEST_COMPRESSION do |dest_io|
open file, "rb" do |source_io|
dest_io << source_io.read(16384) until source_io.eof?
end
end
end
end
end
# lib/capistrano/tasks/assets.rake
namespace :deploy do
desc "Gzip assets"
task :compress_assets do
on roles(fetch(:assets_roles)) do
within release_path do
with rails_env: fetch(:rails_env) do
execute :rake, "assets:compress"
end
end
end
end
end
after "deploy:compile_assets", "deploy:compress_assets"
server {
# ...
location ~* ^/assets/ {
gzip_static on;
expires max;
add_header Cache-Control public;
add_header Last-Modified "";
add_header ETag "";
break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.