How To: Create you own custom Asset Compressor - skamansam/padrino-sprockets GitHub Wiki

When specifying a compressor with the :js_compressor option, you can pass the classname of a custom compressor. We will be creating a new class that uses Uglifier to create a Javascript source map for each compressed file.

Just copy and paste the following code in uglifier_with_source_map_compressor.rb in lib/.

require 'sprockets'
class UglifierWithSourceMapCompressor
  attr_reader :data  # the contents of each file
  attr_reader :file  # the location of each file
  
  def initialize(file, &block)
    @file = file
    @data = block.call
  end
  
  def self.default_mime_type
    'application/javascript'
  end
  
  
  def render(context,options)
    require 'uglifier' unless defined? ::Uglifier
    
    minified  = ''  # the minified version of the js
    sourcemap = ''  # the contents of the source map
    js_file = File.basename(@file)
    
    # Feature detect Uglifier 2.0 option support
    # taken from the Sprockets Uglifier compressor code, with compile() changed to compile_with_map()
    if Uglifier::DEFAULTS[:copyright]
      # Uglifier < 2.x
      minified, sourcemap = Uglifier.new(copyright: false).compile_with_map(data)
    else
      # Uglifier >= 2.x
      minified, sourcemap = Uglifier.new(comments: :none).compile_with_map(data)
    end

    # write the sourcemap to a file somewhere under public
    FileUtils.mkdir_p(Padrino.root('public','js_maps'))
    sourcemap_path = Padrino.root('public','js_maps',js_file+'.map')
    File.truncate(sourcemap_path,0) if File.exists?(sourcemap_path)
    sourcemap_size = IO.write sourcemap_path, sourcemap
    sourcemap_comment = "//@ sourceMappingURL=/js_maps/#{js_file}.map\n"

    #the new compressed javascript content must contain a sourcemap comment
    return minified + sourcemap_comment
  end
end

Now that we have our new compressor, we can now use it. If we only want the map in development mode, and to use the closure compiler in production, we can use the following code in our App class:

    configure :development do
      sprockets :minify=>true , :js_compressor => UglifierWithSourceMapCompressor #, :css_compressor=>:yui
    end
    configure :production do
      sprockets :minify=>true, :js_compressor => :closure
    end