dia nashorner

Embed the <s>Mozilla Rhino</s> Nashorn JavaScript interpreter into Ruby.

Nashorn JS engine is available with Java 8 installs (try jjs -v).

Requirements

Java >= 8

jruby -S gem install dienashorner # make sure you have JRuby >= 1.7.x

Features

require 'nashorn'
include Nashorn
eval_js "'1' + '' * 2" #=> "10"

Nashorn::Context.open do |js| js = MyMath.new js.eval(“math.plus(20, 21)”) #=> 42 end

* make a Ruby object a JavaScript (global) environment

ruby math = MyMath.new Nashorn::Context.open(:with => math) do |js| js.eval(“plus(20, 21)”) #=> 42 end


### Context Options

Mostly the same as with **`jjs`** e.g. `Nashorn::Context.open(:strict => true)`.


### Loading .js

ruby File.open('_.js') { |file| eval_js file }



ruby Nashorn::Context.open { |js| js.load('_.js') }


### Configurable Ruby access

Ported over from [Rhino](https://github.com/cowboyd/therubyrhino#configurable-ruby-access)

<!--
By default accessing Ruby objects from JavaScript is compatible with *therubyracer*:
https://github.com/cowboyd/therubyracer/wiki/Accessing-Ruby-Objects-From-JavaScript

Thus you end-up calling arbitrary no-arg methods as if they were JavaScript properties,
since instance accessors (properties) and methods (functions) are indistinguishable :

ruby Nashorn::Context.open do |context| context = Time context.eval('Time.now') end

However, you can customize this behavior and there's another access implementation
that attempts to mirror only attributes as properties as close as possible:

ruby class Foo attr_accessor :bar

def initialize @bar = “bar” end

def check_bar bar == “bar” end end

Rhino::Ruby::Scriptable.access = :attribute Rhino::Context.open do |context| context = Foo context.eval('var foo = new Foo()') context.eval('foo.bar') # get property using reader context.eval('foo.bar = null') # set property using writer context.eval('foo.check_bar()') # called like a function end

If you happen to come up with your own access strategy, just set it directly :

ruby Rhino::Ruby::Scriptable.access = FooApp::BarAccess.instance

-->


### Rhino Compatibility

Nashorn was inspired (and crafted) from Rhino a.k.a **therubyrhino** JRuby gem.
Far from being a drop-in replacement although there's `require 'nashorn/rhino'`.


### Less.rb

[Less.rb](https://github.com/cowboyd/less.rb) seems to be working (with hacks),
for now you will need to :`require 'nashorn/rhino/less'` before `require 'less'`.


### ExecJS

dienashorner gem ships with an [ExecJS][3] compatible runtime, its best to load it
(`require 'nashorn/execjs/load'`) before ExecJS's auto-detection takes place :

ruby gem 'execjs', require: false gem 'dienashorner', platform: :jruby, require: [ 'nashorn/execjs/load', 'execjs' ]

“`

Nashorn

Nashorn JavaScript runtime is part of OpenJDK (available since 8u40).

Copyright © 2016 Karol Bucek. Apache License v2 (see LICENSE for details).