Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

Fix the Ruby => JavaScript conversion of hashes nested within arrays #13

Closed
wants to merge 1 commit into from

2 participants

@TonyStrauss

Issue #12.

@kares
Collaborator

+1 Tony ! just out of curiosity have you tried therubyracer how is it acting related to this issue ?

@TonyStrauss

Actually, the reason I opened this Pull Request is because I have a project using therubyracer and need to port it to JRuby. therubyracer handles this perfectly.

@kares
Collaborator

finally on master as 4d5e2d8 thanks Tony

@kares kares closed this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Feb 9, 2012
This page is out of date. Refresh to see the latest.
Showing with 49 additions and 2 deletions.
  1. +9 −2 lib/rhino/wormhole.rb
  2. +40 −0 spec/rhino/wormhole_spec.rb
View
11 lib/rhino/wormhole.rb
@@ -43,10 +43,17 @@ def array_to_ruby(js_array)
end
def array_to_javascript(rb_array, scope = nil)
+ # First convert all array elements to their javascript equivalents and
+ # then invoke to_java below in order to create a Java array. This allows
+ # arrays with nested hashes to be converted properly.
+ converted_rb_array = rb_array.map do |rb_element|
+ to_javascript(rb_element, scope)
+ end
+
if scope && context = JS::Context.getCurrentContext
- context.newArray(scope, rb_array.to_java)
+ context.newArray(scope, converted_rb_array.to_java)
else
- JS::NativeArray.new(rb_array.to_java)
+ JS::NativeArray.new(converted_rb_array.to_java)
end
end
View
40 spec/rhino/wormhole_spec.rb
@@ -91,6 +91,46 @@
h.prototype.should be_nil # this is how Rhino works !
end
end
+
+ it "converts deeply nested ruby hashes into native objects" do
+ hash = {
+ :array => [
+ {
+ :breed => "Pug"
+ },
+ {
+ :breed => "English Bulldog"
+ },
+ {
+ :breed => [
+ "Pug",
+ "Beagle"
+ ]
+ }
+ ]
+ }
+
+ Rhino.to_javascript(hash).tap do |h|
+ h.should be_kind_of(Rhino::JS::NativeObject)
+
+ a = h.get("array", h)
+ a.should be_kind_of(Rhino::JS::NativeArray)
+
+ element0 = a.get(0,a)
+ element0.should be_kind_of(Rhino::JS::NativeObject)
+ element0.get("breed", element0).should == "Pug"
+
+ element2 = a.get(2,a)
+ element2.should be_kind_of(Rhino::JS::NativeObject)
+
+ nested_array = element2.get("breed", element2)
+ nested_array.should be_kind_of(Rhino::JS::NativeArray)
+ nested_array.get(0,nested_array).should == "Pug"
+ nested_array.get(1,nested_array).should == "Beagle"
+
+ h.prototype.should be_nil # this is how Rhino works !
+ end
+ end
describe "with a scope" do
Something went wrong with that request. Please try again.