dienashorner 0.1.1

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 1ca8cc68b27b38c33dbdb7f1e0ac5822305ff736
4
+ data.tar.gz: aa5411ac802f8ff7e4dac8a88a3772b1eb392f0b
5
+ SHA512:
6
+ metadata.gz: 79d0770cf58dfe94314196ed577a06291f61427e200c66ef4cdc066017e093f4bd2f5123ce36f2f4884244820372be08e370c0bd390ec6d0fa3256a6bc389023
7
+ data.tar.gz: 4b0a046d56d0878788299b90b85a46e46fb4777fc7d5c0ac78270c043c59a6a11949f2f5633db682020fe2639ba2f83fd8748f98684294d6ac28803326eb153a
data/.gitignore ADDED
@@ -0,0 +1,8 @@
1
+ .idea
2
+ nbproject
3
+ doc
4
+ *.gem
5
+ .rvmrc
6
+ .bundle
7
+ Gemfile.lock
8
+ spec/deprecations.log
data/.rspec ADDED
@@ -0,0 +1 @@
1
+ --color --backtrace --format documentation
data/Gemfile ADDED
@@ -0,0 +1,13 @@
1
+ source "https://rubygems.org"
2
+
3
+ gemspec
4
+
5
+ group :test do
6
+ # NOTE: some specs might be excluded @see #spec/spec_helper.rb
7
+ #gem 'redjs', :git => 'git://github.com/cowboyd/redjs.git', :group => :test,
8
+ # :ref => "0d844f066666f967a78b20beb164c52d9ac3f5ca"
9
+ gem 'less', '~> 2.6.0', :require => false
10
+ gem 'execjs', '2.6.0', :require => false
11
+ end
12
+
13
+ gem 'rake', :require => false, :group => :development
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright (c) 2016 [Karol Bucek](http://kares.org)
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,157 @@
1
+ # dia nashorner
2
+
3
+ Embed the ~~Mozilla Rhino~~ Nashorn JavaScript interpreter into Ruby.
4
+
5
+ Nashorn JS engine is available with Java 8 installs (try `jjs -v`).
6
+
7
+
8
+ ### Requirements
9
+
10
+ Java **>= 8**
11
+
12
+ `jruby -S gem install dienashorner` # make sure you have JRuby >= 1.7.x
13
+
14
+
15
+ ### Features
16
+
17
+ * Evaluate JavaScript bits from the Ruby side
18
+ * Embed Ruby objects into the JavaScript world
19
+
20
+ ```ruby
21
+ require 'nashorn'
22
+ ```
23
+
24
+ * evaluate some simple JavaScript
25
+ ```ruby
26
+ Nashorn.eval 'true + 100' #=> 101
27
+ Nashorn.eval_js '"4" + 2' #=> "42"
28
+ ```
29
+
30
+ ```ruby
31
+ include Nashorn
32
+ eval_js "'1' + '' * 2" #=> "10"
33
+ ```
34
+
35
+ * if you need more control, use a `Context`
36
+ ```ruby
37
+ Nashorn::Context.open do |js|
38
+ js['foo'] = "bar"
39
+ js.eval('foo') # => "bar"
40
+ end
41
+ ```
42
+
43
+ * evaluate a Ruby function from JavaScript
44
+ ```ruby
45
+ Nashorn::Context.open do |js|
46
+ js['say'] = lambda { |word, times| word * times }
47
+ js.eval("say('Szia', 3) + '!'") #=> SziaSziaSzia!
48
+ end
49
+ ```
50
+
51
+ * embed a Ruby object into your JavaScript environment
52
+ ```ruby
53
+ class MyMath
54
+ def plus(a, b); a + b + 1 end
55
+ end
56
+
57
+ Nashorn::Context.open do |js|
58
+ js["math"] = MyMath.new
59
+ js.eval("math.plus(20, 21)") #=> 42
60
+ end
61
+ ```
62
+
63
+ * make a Ruby object a JavaScript (global) environment
64
+ ```ruby
65
+ math = MyMath.new
66
+ Nashorn::Context.open(:with => math) do |js|
67
+ js.eval("plus(20, 21)") #=> 42
68
+ end
69
+ ```
70
+
71
+
72
+ ### Context Options
73
+
74
+ Mostly the same as with **`jjs`** e.g. `Nashorn::Context.open(:strict => true)`.
75
+
76
+
77
+ ### Loading .js
78
+
79
+ ```ruby
80
+ File.open('___.js') { |file| eval_js file }
81
+ ```
82
+
83
+ ```ruby
84
+ Nashorn::Context.open { |js| js.load('___.js') }
85
+ ```
86
+
87
+
88
+ ### Configurable Ruby access
89
+
90
+ Ported over from [Rhino](https://github.com/cowboyd/therubyrhino#configurable-ruby-access)
91
+
92
+ <!--
93
+ By default accessing Ruby objects from JavaScript is compatible with *therubyracer*:
94
+ https://github.com/cowboyd/therubyracer/wiki/Accessing-Ruby-Objects-From-JavaScript
95
+
96
+ Thus you end-up calling arbitrary no-arg methods as if they were JavaScript properties,
97
+ since instance accessors (properties) and methods (functions) are indistinguishable :
98
+
99
+ ```ruby
100
+ Nashorn::Context.open do |context|
101
+ context['Time'] = Time
102
+ context.eval('Time.now')
103
+ end
104
+ ```
105
+
106
+ However, you can customize this behavior and there's another access implementation
107
+ that attempts to mirror only attributes as properties as close as possible:
108
+ ```ruby
109
+ class Foo
110
+ attr_accessor :bar
111
+
112
+ def initialize
113
+ @bar = "bar"
114
+ end
115
+
116
+ def check_bar
117
+ bar == "bar"
118
+ end
119
+ end
120
+
121
+ Rhino::Ruby::Scriptable.access = :attribute
122
+ Rhino::Context.open do |context|
123
+ context['Foo'] = Foo
124
+ context.eval('var foo = new Foo()')
125
+ context.eval('foo.bar') # get property using reader
126
+ context.eval('foo.bar = null') # set property using writer
127
+ context.eval('foo.check_bar()') # called like a function
128
+ end
129
+ ```
130
+
131
+ If you happen to come up with your own access strategy, just set it directly :
132
+ ```ruby
133
+ Rhino::Ruby::Scriptable.access = FooApp::BarAccess.instance
134
+ ```
135
+ -->
136
+
137
+
138
+ ### Rhino Compatibility
139
+
140
+ Nashorn was inspired (and crafted) from Rhino a.k.a **therubyrhino** JRuby gem.
141
+ Far from being a drop-in replacement although there's `require 'nashorn/rhino'`.
142
+
143
+
144
+ ### Less.rb
145
+
146
+ [Less.rb](https://github.com/cowboyd/less.rb) seems to be working, for now you
147
+ will simply need to :`require 'nashorn/rhino/less'` before a `require 'less'`.
148
+
149
+
150
+ ### Nashorn
151
+
152
+ Nashorn JavaScript runtime is part of OpenJDK http://openjdk.java.net/projects/nashorn/
153
+
154
+
155
+ ## Copyright
156
+
157
+ Copyright (c) 2016 Karol Bucek. Apache License v2 (see LICENSE for details).
data/Rakefile ADDED
@@ -0,0 +1,18 @@
1
+
2
+ task :default => :spec
3
+
4
+ begin
5
+ require 'bundler/setup'
6
+ rescue LoadError => e
7
+ warn "Bundler not available: #{e.inspect}"
8
+ else
9
+ require 'bundler/gem_tasks'
10
+ Bundler::GemHelper.install_tasks
11
+ end
12
+
13
+ require 'rspec/core'
14
+ require 'rspec/core/rake_task'
15
+ RSpec::Core::RakeTask.new(:spec) do |spec|
16
+ spec.pattern = 'spec/**/*_spec.rb'
17
+ spec.rspec_opts = '--color'
18
+ end
@@ -0,0 +1,24 @@
1
+ # -*- encoding: utf-8 -*-
2
+
3
+ Gem::Specification.new do |gem|
4
+ gem.name = 'therubyrhino becomes dienashorner'.split.last
5
+ gem.authors = ['Karol Bucek']
6
+ gem.email = ['self@kares.org']
7
+ gem.licenses = ['Apache-2.0']
8
+
9
+ path = File.expand_path("lib/nashorn/version.rb", File.dirname(__FILE__))
10
+ gem.version = File.read(path).match( /.*VERSION\s*=\s*['"](.*)['"]/m )[1]
11
+
12
+ gem.summary = %q{The Nashorn JavaScript interpreter for JRuby}
13
+ gem.description = %q{Nashorn, a Rhino's sucessor, allows embeded JavaScript interaction from Ruby.}
14
+ gem.homepage = "https://github.com/kares/dienashorner"
15
+
16
+ gem.require_paths = ["lib"]
17
+ gem.files = `git ls-files`.split("\n").sort
18
+ gem.test_files = `git ls-files -- {spec}/*`.split("\n")
19
+
20
+ gem.extra_rdoc_files = %w[ README.md LICENSE ]
21
+
22
+ gem.add_development_dependency "rspec", "~> 2.14.1"
23
+ gem.add_development_dependency "mocha", "~> 0.13.3"
24
+ end
@@ -0,0 +1,188 @@
1
+ require 'stringio'
2
+
3
+ module Nashorn
4
+
5
+ # JavaScript gets executed in a context which represents the execution environment
6
+ # in which scripts run. The environment consists of the standard JavaScript objects
7
+ # and functions like `Object`, `parseInt()` or `null`, as well as any objects or
8
+ # functions which have been defined in it. e.g.
9
+ #
10
+ # Context.open do |js|
11
+ # js['answer'] = 22
12
+ # js['compute'] = lambda { |t| 10 * t }
13
+ # js.eval('num + compute(2)') #=> 42
14
+ # end
15
+ #
16
+ # @note Context are isolated, multiple context do not share any JS objects!
17
+ class Context
18
+
19
+ class << self
20
+
21
+ def open(options = nil, &block)
22
+ new(options).open(&block)
23
+ end
24
+
25
+ def eval(source, options = nil)
26
+ new(options).eval(source)
27
+ end
28
+
29
+ end
30
+
31
+ # @private
32
+ ENGINE_SCOPE = javax.script.ScriptContext.ENGINE_SCOPE
33
+ # @private
34
+ NashornScriptEngineFactory = JS::NashornScriptEngineFactory
35
+ # @private
36
+ NASHORN_GLOBAL = JS::NashornScriptEngine::NASHORN_GLOBAL.to_java
37
+ # @private
38
+ SimpleScriptContext = javax.script.SimpleScriptContext
39
+
40
+ # Create a new JavaScript environment for executing JS (and Ruby) code.
41
+ def initialize(options = nil)
42
+ if options.is_a?(Hash)
43
+ factory = options[:factory]
44
+ with = options[:with]
45
+ java = options[:java]
46
+ version = options[:javascript_version] || options[:language_version]
47
+ if version
48
+ (args ||= []).push '--language', version.to_s
49
+ end
50
+ if options.key?(:strict)
51
+ (args ||= []).push '-strict', (!!options[:strict]).to_s
52
+ end
53
+ if options.key?(:scripting)
54
+ (args ||= []).push '-scripting', (!!options[:scripting]).to_s
55
+ end
56
+ elsif options.is_a?(String)
57
+ args = options.split(' ')
58
+ elsif options.is_a?(Array)
59
+ args = options
60
+ end
61
+ factory ||= NashornScriptEngineFactory.new
62
+ with ||= nil
63
+ java = true if java.nil?
64
+
65
+ @native = args ? factory.getScriptEngine(args.to_java) : factory.getScriptEngine
66
+
67
+ #simple_context = SimpleScriptContext.new
68
+ #bindings = @native.getBindings(ENGINE_SCOPE)
69
+ #global = bindings.get(NASHORN_GLOBAL)
70
+
71
+ @scope = global = @native.eval('this')
72
+
73
+ if with
74
+ #bindings.set(NASHORN_GLOBAL, @scope = Nashorn.to_js(with))
75
+ object = @native.eval('Object')
76
+ @native.invokeMethod(object, 'bindProperties', global, Nashorn.to_js(with))
77
+ end
78
+ unless java
79
+ [ 'java', 'javax', 'org', 'com', 'Packages', 'Java' ].each do |name|
80
+ global.removeMember(name)
81
+ end
82
+ end
83
+ yield(self) if block_given?
84
+ end
85
+
86
+ def factory; @native.getFactory end
87
+
88
+ # Read a value from the global scope of this context
89
+ def [](key)
90
+ @scope[key]
91
+ end
92
+
93
+ # Set a value in the global scope of this context. This value will be visible to all the
94
+ # javascript that is executed in this context.
95
+ def []=(key, val)
96
+ @scope[key] = val
97
+ end
98
+
99
+ # Evaluate a String/IO of JavaScript in this context.
100
+ def eval(source, source_name = "<eval>", line_number = 1)
101
+ open do
102
+ if IO === source || StringIO === source
103
+ source = IOReader.new(source)
104
+ else
105
+ source = source.to_s
106
+ end
107
+ Nashorn.to_rb @native.eval(source, @scope)
108
+ end
109
+ end
110
+
111
+ def evaluate(source); eval(source) end
112
+
113
+ # Read the contents of <tt>filename</tt> and evaluate it as JavaScript.
114
+ #
115
+ # Context.open { |js_env| js_env.load("path/to/some/lib.js") }
116
+ #
117
+ # @return the result of evaluating the JavaScript
118
+ def load(filename)
119
+ File.open(filename) do |file|
120
+ eval file, filename
121
+ end
122
+ end
123
+
124
+ def language_version
125
+ factory.getLanguageVersion
126
+ end
127
+
128
+ # Get the JavaScript language version.
129
+ # @private
130
+ def javascript_version
131
+ case version = language_version
132
+ when nil, '' then nil
133
+ #when 'es5' then 1.5 # default
134
+ #when 'es6' then 1.6
135
+ else version
136
+ end
137
+ end
138
+ alias :version :javascript_version
139
+
140
+ # @private
141
+ def javascript_version=(version)
142
+ warn "#{self}#javascript_version = not supported, use open(javascript_version: #{version.inspect}) instead"
143
+ end
144
+ alias :version= :javascript_version=
145
+
146
+ # @private
147
+ ScriptException = javax.script.ScriptException
148
+
149
+ def open
150
+ yield self
151
+ rescue ScriptException => e
152
+ raise JSError.new(e)
153
+ rescue JS::NashornException => e
154
+ raise JSError.new(e)
155
+ end
156
+
157
+ end
158
+
159
+ # @private
160
+ class IOReader < java.io.Reader
161
+
162
+ def initialize(io)
163
+ @io = io
164
+ end
165
+
166
+ # int Reader#read(char[] buffer, int offset, int length)
167
+ def read(buffer, offset, length)
168
+ str = nil
169
+ begin
170
+ str = @io.read(length)
171
+ rescue StandardError => e
172
+ raise java.io.IOException.new("failed reading from ruby IO object: #{e.inspect}")
173
+ end
174
+ return -1 if str.nil?
175
+
176
+ jstr = str.to_java
177
+ for i in 0 .. jstr.length - 1
178
+ buffer[i + offset] = jstr.charAt(i)
179
+ end
180
+ return jstr.length
181
+ end
182
+
183
+ end
184
+
185
+ # @private not used
186
+ class ContextError < StandardError; end
187
+
188
+ end
@@ -0,0 +1,57 @@
1
+ class << Nashorn
2
+
3
+ def to_rb(object, unmirror = false)
4
+ # ConsString for optimized String + operations :
5
+ return object.toString if object.is_a?(Java::JavaLang::CharSequence)
6
+ return object.unwrap if object.is_a?(Nashorn::RubyObject)
7
+ return object.unwrap if object.is_a?(Nashorn::RubyFunction)
8
+ return nil if Nashorn::JS::ScriptObjectMirror.isUndefined(object)
9
+ return js_mirror_to_rb(object) if unmirror
10
+ object
11
+ end
12
+ alias_method :to_ruby, :to_rb
13
+
14
+ def to_js(object)
15
+ case object
16
+ when NilClass then object
17
+ when String, Numeric then object.to_java
18
+ when TrueClass, FalseClass then object.to_java
19
+ when Nashorn::JS::JSObject then object
20
+ #when Array then array_to_js(object)
21
+ #when Hash then hash_to_js(object)
22
+ when Time then object.to_java
23
+ when Method, UnboundMethod then Nashorn::Ruby::Function.wrap(object)
24
+ when Proc then Nashorn::Ruby::Function.wrap(object)
25
+ when Class then Nashorn::Ruby::Constructor.wrap(object)
26
+ else Nashorn::Ruby::Object.wrap(object)
27
+ end
28
+ end
29
+ alias_method :to_javascript, :to_js
30
+
31
+ def args_to_rb(args)
32
+ args.map { |arg| to_rb(arg) }
33
+ end
34
+
35
+ def args_to_js(args)
36
+ args.map { |arg| to_js(arg) }.to_java
37
+ end
38
+
39
+ DEEP_MIRROR = ENV['nashorn.to_rb.unmirror.deep'] &&
40
+ ENV['nashorn.to_rb.unmirror.deep'].length > 0 &&
41
+ ENV['nashorn.to_rb.unmirror.deep'] != 'false'
42
+
43
+ def js_mirror_to_rb(object, deep = DEEP_MIRROR)
44
+ object = Nashorn::JS::ScriptUtils.unwrap(object)
45
+ if object.is_a?(Nashorn::JS::JSObject)
46
+ return object.values.to_a if object.isArray
47
+ return object if object.isFunction
48
+ # Nashorn::JS::ScriptObjectMirror is already a Map but still :
49
+ hash = {}
50
+ object.keySet.each { |key| hash[key] = to_rb object[key], true }
51
+ hash
52
+ else
53
+ object
54
+ end
55
+ end
56
+
57
+ end