-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathcoffee_script.rb
More file actions
81 lines (67 loc) · 1.94 KB
/
coffee_script.rb
File metadata and controls
81 lines (67 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
require 'execjs'
require 'coffee_script/source'
module CoffeeScript
Error = ExecJS::Error
EngineError = ExecJS::RuntimeError
CompilationError = ExecJS::ProgramError
module Source
def self.path
@path ||= ENV['COFFEESCRIPT_SOURCE_PATH'] || bundled_path
end
def self.path=(path)
@contents = @version = @bare_option = @context = nil
@path = path
end
COMPILE_FUNCTION_SOURCE = <<-JS
;function compile(script, options) {
try {
var result = CoffeeScript.compile(script, options);
if (options.sourceMap === "v3" && result.sourceMap)
delete result.sourceMap;
return result;
} catch (err) {
if (err instanceof SyntaxError && err.location) {
throw new SyntaxError([
err.filename || "[stdin]",
err.location.first_line + 1,
err.location.first_column + 1
].join(":") + ": " + err.message)
} else {
throw err;
}
}
}
JS
def self.contents
@contents ||= File.read(path) + COMPILE_FUNCTION_SOURCE
end
def self.version
@version ||= contents[/CoffeeScript Compiler v([\d.]+)/, 1]
end
def self.bare_option
@bare_option ||= contents.match(/noWrap/) ? 'noWrap' : 'bare'
end
def self.context
@context ||= ExecJS.compile(contents)
end
end
class << self
def engine
end
def engine=(engine)
end
def version
Source.version
end
# Compile a script (String or IO) to JavaScript.
def compile(script, options = {})
script = script.read if script.respond_to?(:read)
unless options.key?(:bare)
options[:bare] = options.key?(:no_wrap) ? options[:no_wrap] : false
end
# Stringify keys
options = options.inject({}) { |h, (k, v)| h[k.to_s] = v; h }
Source.context.call("compile", script, options)
end
end
end