class NodeRunner::Executor
Attributes
name[R]
Public Class Methods
new(options = {})
click to toggle source
# File lib/node-runner.rb, line 86 def initialize(options = {}) @command = options[:command] || ['node'] @modules_path = options[:modules_path] || File.join(Dir.pwd, "node_modules") @runner_path = options[:runner_path] || File.join(File.expand_path(__dir__), '/node_runner.js') @encoding = options[:encoding] || "UTF-8" @binary = nil @popen_options = {} @popen_options[:external_encoding] = @encoding if @encoding @popen_options[:internal_encoding] = ::Encoding.default_internal || 'UTF-8' if @runner_path instance_eval generate_compile_method(@runner_path) end end
Public Instance Methods
exec(filename)
click to toggle source
# File lib/node-runner.rb, line 102 def exec(filename) ENV["NODE_PATH"] = @modules_path stdout, stderr, status = Open3.capture3("#{binary} #{filename}") if status.success? stdout else raise exec_runtime_error(stderr) end end
Protected Instance Methods
binary()
click to toggle source
# File lib/node-runner.rb, line 114 def binary @binary ||= which(@command) end
encode_source(source)
click to toggle source
# File lib/node-runner.rb, line 148 def encode_source(source) encoded_source = encode_unicode_codepoints(source) ::JSON.generate("(function(){ #{encoded_source} })()", quirks_mode: true) end
encode_unicode_codepoints(str)
click to toggle source
# File lib/node-runner.rb, line 153 def encode_unicode_codepoints(str) str.gsub(/[\u0080-\uffff]/) do |ch| "\\u%04x" % ch.codepoints.to_a end end
exec_runtime_error(output)
click to toggle source
# File lib/node-runner.rb, line 159 def exec_runtime_error(output) error = RuntimeError.new(output) lines = output.split("\n") lineno = lines[0][/:(\d+)$/, 1] if lines[0] lineno ||= 1 error.set_backtrace(["(node_runner):#{lineno}"] + caller) error end
generate_compile_method(path)
click to toggle source
# File lib/node-runner.rb, line 138 def generate_compile_method(path) <<-RUBY def compile_source(source, args, func) <<-RUNNER #{IO.read(path)} RUNNER end RUBY end
locate_executable(command)
click to toggle source
# File lib/node-runner.rb, line 118 def locate_executable(command) commands = Array(command) exts = ENV['PATHEXT'] ? ENV['PATHEXT'].split(';') : [''] exts << '' commands.find { |cmd| if File.executable? cmd cmd else path = ENV['PATH'].split(File::PATH_SEPARATOR).flat_map { |p| exts.map { |e| File.join(p, "#{cmd}#{e}") } }.find { |p| File.executable?(p) && File.file?(p) } path && File.expand_path(path) end } end
which(command)
click to toggle source
# File lib/node-runner.rb, line 168 def which(command) Array(command).find do |name| name, args = name.split(/\s+/, 2) path = locate_executable(name) next unless path args ? "#{path} #{args}" : path end end