Xenofex
1/18/2016 - 11:11 AM

An initializer to enable source maps for coffee script in Rails 4.2.5/Sprockets 3.5.2

An initializer to enable source maps for coffee script in Rails 4.2.5/Sprockets 3.5.2

if Rails.env.development?
  require "base64"

  module Sprockets
    module CoffeeScriptProcessor
      DEFAULT_OPTIONS = { "sourceMap" => true }

      def self.call(input)
        data = input[:data]
        input[:cache].fetch([self.cache_key, data]) do
          result = Autoload::CoffeeScript.compile(data, DEFAULT_OPTIONS)

          source_map = result['v3SourceMap']
          parsed_source_map = MultiJson.decode(source_map)
          parsed_source_map['sources'] = [File.basename(input[:filename])]
          parsed_source_map['sourcesContent'] = [data]

          result['js'] + "\n//# sourceMappingURL=data:application/json;base64," + Base64.strict_encode64(MultiJson.encode(parsed_source_map))
        end
      end
    end
  end
end