Read more

Capistrano + Rails: Automatically skipping asset compilation when assets have not changed

Dominik Schöler
May 16, 2018Software engineer at makandra GmbH

In medium-sized to large Rails applications, asset compilation can take several minutes. In order to speed up deployment, asset precompilation can be skipped. This card automates the process.

Capistrano 3

namespace :deploy do
  
  desc 'Automatically skip asset compile if possible'
  task :auto_skip_assets do
    asset_locations = %r(^(Gemfile\.lock|app/assets|lib/assets|vendor/asset))

    revisions = []
    on roles :app do
      within current_path do
        revisions << capture(:cat, 'REVISION').strip
      end
    end

    # Never skip asset compile when servers are running on different code
    next if revisions.uniq.length > 1

    changed_files = `git diff --name-only #{revisions.first}`.split
    if changed_files.grep(asset_locations).none?
      puts Airbrussh::Colors.green('** Assets have not changed since last deploy.')
      invoke 'deploy:skip_assets'
    end
  end

  desc 'Skip asset compile'
  task :skip_assets do
    puts Airbrussh::Colors.yellow('** Skipping asset compile.')
    Rake::Task['deploy:assets:precompile'].clear_actions
  end

end
Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

To use this for all stages, add this line to your Capfile:

before 'deploy:starting', 'deploy:auto_skip_assets'

I have been using this in production successfully. To activate it for staging only, put that line into config/deploy/staging.rb instead.

Note that skip_assets is a separate task, so you'll still be able to skip assets manually.

Posted by Dominik Schöler to makandra dev (2018-05-16 15:47)