Sha256: b57b06a982de27e70d8147231f1d76cd0b5851660a5549eda98fe4c59fed9658

Contents?: true

Size: 1.18 KB

Versions: 2

Compression:

Stored size: 1.18 KB

Contents

require 'sprockets'
require 'tilt'

module Sprockets
  class CommonJS < Tilt::Template

    WRAPPER = '%s.define({%s:' +
                     'function(exports, require, module){' +
                     '%s' +
                     ";}});\n"

    EXTENSIONS = %w{.module .cjs}

    class << self
      attr_accessor :default_namespace
    end

    self.default_mime_type = 'application/javascript'
    self.default_namespace = 'this.require'

    protected

    def prepare
      @namespace = self.class.default_namespace
    end

    def evaluate(scope, locals, &block)
      if commonjs_module?(scope)
        scope.require_asset 'sprockets/commonjs'
        WRAPPER % [ namespace, module_name(scope), data ]
      else
        data
      end
    end

    private

    attr_reader :namespace

    def commonjs_module?(scope)
      EXTENSIONS.include?(File.extname(scope.logical_path))
    end

    def module_name(scope)
      scope.logical_path.
        gsub(/^\.?\//, ''). # Remove relative paths
        chomp('.module').   # Remove module ext
        inspect
    end

  end

  register_postprocessor 'application/javascript', CommonJS
  append_path File.expand_path('../../../assets', __FILE__)
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
sprockets-commonjs-0.0.6 lib/sprockets/commonjs.rb
sprockets-commonjs-0.0.6.rc1 lib/sprockets/commonjs.rb