johnthethird
8/3/2012 - 4:05 PM

Parallelize assets:precompile

Parallelize assets:precompile

require 'parallel' # gem install parallel (https://github.com/grosser/parallel)

# Monkey patch to Sprockets::StaticCompiler, a class provided by actionpack
# that's used by the assets:precompile task. This patch uses the Parallel gem
# to parallelize asset compilation in the simplest way possible.
#
# Parallel wraps Process.fork to handle things like inter-process communication
# via pipes and determining the maximum number of processes to run based on
# your system's total logical processors. So far only tested on MRI 1.9.3 on OS X.
module Sprockets
  class StaticCompiler
    def compile
      files_to_compile = []

      env.each_logical_path do |logical_path|
        files_to_compile << logical_path if compile_path?(logical_path)
      end
 
      results = Parallel.map(files_to_compile) do |logical_path|
        if asset = env.find_asset(logical_path)
          start = Time.now
          compiled_path = write_asset(asset) # This is where compilation actually happens
          puts "Compiled #{logical_path} (#{Time.now - start} sec)"
          [logical_path, compiled_path]
        end
      end

      manifest = {}
      results.compact.each {|(path, compiled_path)| manifest[path] = compiled_path}
      write_manifest(manifest) if @manifest
    end
  end
end