Skip to content

Instantly share code, notes, and snippets.

@jeremywadsack
Last active May 5, 2016 18:43
Show Gist options
  • Save jeremywadsack/70d1535582be797c1539 to your computer and use it in GitHub Desktop.
Save jeremywadsack/70d1535582be797c1539 to your computer and use it in GitHub Desktop.
Rails 4.2, Capistrano 3.4 local asset precompilation using rsync
# lib/capistrano/tasks/assets.rake
namespace :deploy do
desc "Precompile assets locally and then rsync to web servers"
task :compile_assets => [:set_rails_env] do
run_locally do
with rails_env: :production do
execute "bundle exec rake assets:precompile"
end
end
on release_roles(fetch(:assets_roles)) do |server|
# Have to remove manifest files first because Sprockets reads the first manifest file it finds
within release_path do
with rails_env: fetch(:rails_env) do
execute :rm, "./public/#{fetch(:assets_prefix)}/manifest-*"
end
end
run_locally do
execute "rsync -av ./public/#{fetch(:assets_prefix)}/ #{server.user}@#{server.hostname}:#{shared_path}/public/#{fetch(:assets_prefix)}/"
end
end
run_locally do
execute "rm -rf public/assets"
end
end
desc "Cleanup expired assets"
task :cleanup_assets => [:set_rails_env] do
next unless fetch(:keep_assets)
on release_roles(fetch(:assets_roles)) do
within release_path do
with rails_env: fetch(:rails_env) do
execute :rake, "'assets:clean[#{fetch(:keep_assets)}]'"
end
end
end
end
after :updated, "deploy:compile_assets"
after "deploy:updated", "deploy:cleanup_assets"
task :set_linked_dirs do
set :linked_dirs, fetch(:linked_dirs, []).push("public/#{fetch(:assets_prefix)}")
end
end
after "deploy:set_rails_env", "deploy:set_linked_dirs"
namespace :load do
task :defaults do
set :assets_roles, fetch(:assets_roles, [:web])
set :assets_prefix, fetch(:assets_prefix, "assets")
end
end
@jeremywadsack
Copy link
Author

Revised this because it was leaving old manifest-md5hash.json files in production. Sprockets apparently reads the first such file it finds (by filename) and loads that version of the assets. So the production assets were getting pinned by the earlier hash fingerprint.

Also used the rake assets:clean task to remove old assets because we want to keep some around for cached views. Although that doesn't seem to be doing anything for me.

At this point, this really should include capinstrano's backup_manifest and restore_manifest tasks to safely handle deployment failure and not lose the manifest files if it rollsback deployment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment