module Xpring::Javascript

Basic Ruby to Javascript interop

Constants

ENTRY_POINT
LIBRARY_INJECTION_EXPRESSION
LIBRARY_PATH

Public Class Methods

run() { || ... } click to toggle source

@yieldreturn [String] @return [Hash<Symbol, Object>, String, nil]

# File lib/xpring/javascript.rb, line 17
def self.run
  script = prepare(yield)
  cmd = "node -p #{script.dump}"
  Xpring.debug_log(cmd)
  raw = IO.popen(cmd, &:readlines).first&.strip
  parse(raw)
end

Private Class Methods

add_stringify_to(script) click to toggle source
# File lib/xpring/javascript.rb, line 56
def self.add_stringify_to(script)
  script.strip.split(";").tap do |script_array|
    script_array[-1] = "JSON.stringify(#{script_array[-1]})"
  end.join(";").concat(";")
end
parse(result) click to toggle source
# File lib/xpring/javascript.rb, line 25
def self.parse(result)
  from_json = begin
                JSON.parse(result)
              rescue JSON::ParserError
              end
  if from_json.respond_to?(:transform_keys)
    from_json.transform_keys(&:to_sym)
  else
    from_json
  end
end
prepare(script) click to toggle source
# File lib/xpring/javascript.rb, line 38
def self.prepare(script)
  sanitize(raw_script_given(script))
end
raw_script_given(script) click to toggle source
# File lib/xpring/javascript.rb, line 48
def self.raw_script_given(script)
  [
    LIBRARY_INJECTION_EXPRESSION,
    add_stringify_to(script),
  ].join
end
sanitize(script) click to toggle source
# File lib/xpring/javascript.rb, line 43
def self.sanitize(script)
  script.strip.tr("\"", "\\\"").gsub(/[\n\r]/, "").gsub(/\s{2,}/, "")
end