Skip to content

Instantly share code, notes, and snippets.

@wagenet
Created March 9, 2012 01:12
Show Gist options
  • Save wagenet/2004454 to your computer and use it in GitHub Desktop.
Save wagenet/2004454 to your computer and use it in GitHub Desktop.
require 'rake-pipeline'
module Neuter
class SpadeWrapper < Rake::Pipeline::FileWrapper
class << self
# FIXME: This is probably not threadsafe
def batch(config)
@config = config
@required = []
yield
ensure
@required = nil
@config = nil
end
def required?(req)
@required.include?(req)
end
def required(req)
@required << req
end
def strip_requires(source)
requires = []
regexp = @config && @config[:require_regexp] || %r{^\s*require\(['"]([^'"]*)['"]\);?\s*}
# FIXME: This $1 may not be reliable with other regexps
source.gsub!(regexp){ requires << $1; '' }
requires
end
def transform_path(path)
@config && @config[:path_transform] ? @config[:path_transform].call(path) : path
end
def closure_wrap(source)
@config && @config[:closure_wrap] ? "(function() {\n#{source}\n})();\n\n" : source
end
end
def read
klass = self.class
source = super
requires = klass.strip_requires(source).reject{|req| klass.required?(req) }
required_files = requires.map do |req|
klass.required(req)
req_path = klass.transform_path(req)
klass.new(root, req_path, encoding).read
end
file = "/* #{path} */\n\n#{klass.closure_wrap(source)}"
(required_files << file).join("\n\n")
end
end
module Filters
class NeuterFilter < Rake::Pipeline::ConcatFilter
def initialize(string=nil, config={}, &block)
if string.is_a?(Hash)
config = string
string = nil
end
@config = config
super(string, &block)
end
def generate_output(inputs, output)
inputs.each do |input|
SpadeWrapper.batch(@config) do
spade = SpadeWrapper.new(input.root, input.path, input.encoding)
output.write spade.read
end
end
end
end
end
module Helpers
def neuter(*args, &block)
filter(Neuter::Filters::NeuterFilter, *args, &block)
end
end
end
Rake::Pipeline::DSL::PipelineDSL.send(:include, Neuter::Helpers)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment