Re: [therubyracer] Hash from Ruby can't be modified in JavaScript

123 views
Skip to first unread message

Charles Lowell

unread,
Apr 16, 2013, 9:54:12 AM4/16/13
to therub...@googlegroups.com

On Apr 15, 2013, at 3:05 PM, Tomáš Linhart wrote:

Hello,

I have Ruby class 

class Test

  attr_accessor :test,

  def initialize(test)
    @test = test
  end

end

And I create a new instance and assign a new hash - Test.new(Hash.new) after that I pass this instance into V8::Function via call method but when I modify this test property in JavaScript and create new field then it is not visible back in Ruby so it means I can't change hashes in JavaScript. 

What can I do?

Tomáš,

The default conversion for Hash (in lib/v8/conversion/hash.rb) copies the object, but you can change the conversion to pass a reference through to JavaScript. Conversions can be set globally, per context, or per object, so you can change the conversion on the actual hash object:

class Test
  attr_accessor :test

  def test=(hash)
    # modify how this hash is sent to v8 by defining a to_v8() method
    # pass by reference
    def hash.to_v8
      V8::Conversion::Reference.construct! hash
    end
    @test = test
   end

  def initialize(test)
    self.test = test
  end
end


Alternatively, you can wrap the Hash in another object which will achieve the same effect (since the default conversion is to pass by reference).

class HashWrapper
  def initialize(hash)
    @hash = hash
  end
  def [](key)
    @hash[key]
  end
  def []=(key,value)
    @hash[key] = value
  end
end

class Test
  attr_reader :test

  def test=(hash)
    @test = HashWrapper.new(hash)
  end

  def initialize(test)
    self.test = test
  end
end
    


Hope that helps!

cheers,
Charles


Thanks.
Tomáš

--
You received this message because you are subscribed to the Google Groups "The Ruby Racer" group.
To unsubscribe from this group and stop receiving emails from it, send an email to therubyracer...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Charles Lowell 
thefrontside.net | twitter: @cowboyd | github: cowboyd




Reply all
Reply to author
Forward
0 new messages