RunJS
With RunJS you can run JavaScript code from Ruby.
require 'runjs'
puts RunJS.run('return "Hello World";')Installation
$ gem install runjsRunJS depends on the json library. Starting with Ruby version 1.9 this is included, but on Ruby 1.8 you have to install the json gem. If this causes any problems, install the json_pure gem instead.
$ gem install json || gem install json_pureJavaScript Runtimes
Supported runtimes
- TheRubyRacer
- JavaScriptCore included with OS X
- V8
- Node
- JScript on Windows
RunJS will automatically select the first available runtime from the list above.
Deprecated runtimes
To use TheRubyRhino or SpiderMonkey you have to set the runtime manually.
Set the runtime
You can control which runtime RunJS uses in your Ruby code.
RunJS.runtime = RunJS::NodeOr with the RUNJS_RUNTIME environment variable.
$ export RUNJS_RUNTIME=NodeExamples
require 'runjs'
RunJS.run('return 2 + 2;') # => 4
RunJS.call('Math.sqrt', 25) # => 5
RunJS.apply('Array.prototype.slice', '"cat"') # => ["c", "a", "t"]Compiling CoffeeScript
require 'runjs'
require 'open-uri'
url = 'http://jashkenas.github.com/coffee-script/extras/coffee-script.js'
compiler = open(url).read
coffee = 'alert yes'
options = { header: true, bare: true }
RunJS.context(compiler).apply('CoffeeScript.compile', 'CoffeeScript', coffee, options)
# => // Generated by CoffeeScript 1.6.3
# => alert(true);Credits
Thanks to Sam Stephenson, Joshua Peek and the other contributors to ExecJS. Although none of the code is directly copied, the API and code structure is almost identical. While coding, the ExecJS code was consulted all the time, and RunJS ended up like a rewrite of ExecJS.
License
Copyright (c) 2013 AS Harbitz.
RunJS is released under the MIT License.