Skip to content

Instantly share code, notes, and snippets.

@timscott
Last active April 4, 2016 19:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timscott/636f641fe22046695bf0705bd36b92a7 to your computer and use it in GitHub Desktop.
Save timscott/636f641fe22046695bf0705bd36b92a7 to your computer and use it in GitHub Desktop.
A utility class to build Javascript from CoffeeScript. Builds single file, a folder, or a tree. Optional rebuild supports lazy building in production. Specify a lib directory.
require 'coffee-rails'
require 'fileutils'
class JsBuilder
def initialize(base_directory:, bin_folder: 'bin', lib_directory: File.join(base_directory, 'lib'), rebuild: false)
@base_directory = base_directory
@lib_directory = lib_directory
@bin_folder = bin_folder
@rebuild = rebuild
end
def build(relative_path:, deep: true)
path = ensure_path relative_path
filepaths = if File.directory? path
Dir["#{path}/#{'**/' if deep}*.coffee"]
else
[path]
end
js_filepaths = filepaths.each(&method(:compile))
lib_filepaths = Dir["#{@lib_directory}/**/*.coffee"]
lib_js_filepaths = lib_filepaths.each(&method(:compile))
[js_filepaths, lib_js_filepaths]
end
def clean(relative_path:, deep: true)
path = ensure_path relative_path
directories = Dir.glob "#{path}/#{'**/' if deep}"
directories.each do |directory|
bin_directory = File.join directory, @bin_folder
FileUtils.rm_rf bin_directory
end
end
private
def compile(filepath)
directory = File.dirname filepath
filename = File.basename filepath, '.coffee'
if @rebuild
bin_directory = File.join directory, @bin_folder
FileUtils.rm_rf bin_directory
end
js_path = "#{File.join bin_directory, filename}.js"
return js_path if File.exists?(js_path)
file = File.open filepath
js = CoffeeScript.compile file
create_file js_path, js
js_path
end
def create_file(path, content)
dirname = File.dirname path
FileUtils.mkdir_p dirname unless File.directory? dirname
File.open(path, 'w') { |f| f.write content }
end
def ensure_path(relative_path)
path = File.join @base_directory, relative_path
raise "Cannot process javascript; path not found: #{path}" unless File.exist? path
path
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment