Skipping asset precompilation in capistrano if the assets did not change

The default capistrano task for compiling the assets compiles them every time, regardless of whether any assets were changed in the set of commits that you are deploying. This is the code snippet I use to check if the assets have changed:

namespace :deploy do
  namespace :assets do
 
    def not_first_deploy?
      'true' ==  capture("if [ -e #{current_path}/REVISION ]; then echo 'true'; fi").strip
    end
 
    desc "Run the asset precompilation rake task only if there are changes."
    task :precompile, :roles => :web, :except => { :no_release => true } do
      if not_first_deploy?
        from = source.next_revision(current_revision)
        if capture("cd #{latest_release} && #{source.local.log(from)} vendor/assets/ app/assets/ | wc -l").to_i > 0
          run %Q{cd #{latest_release} && #{rake} RAILS_ENV=#{rails_env} #{asset_env} assets:precompile}
        else
          logger.info "Skipping asset pre-compilation because there were no asset changes"
        end
      end
    end
 
  end
end

It’s based in this other snippet. You have to load the file that contains the snippet after loading the default capistrano asset tasks. For example, if the above snippet is in lib/deploy/assets.rb, you should write in your main deploy.rb file something like:

load 'deploy/assets'
load 'lib/deploy/assets'
This entry was posted in rails. Bookmark the permalink.