From b32060c925ccb47349ceb9764cc53c668bc2f9dd Mon Sep 17 00:00:00 2001 From: Charles Lowell Date: Thu, 7 Jun 2012 11:09:13 -0500 Subject: [PATCH] add basic conversions for V8::Object and V8::Array --- lib/v8.rb | 4 +++- lib/v8/array.rb | 13 +++++++++++++ lib/v8/conversion.rb | 38 ++++++++++++++++++++++++++++++++++++-- lib/v8/object.rb | 21 +++++++++++++++++++++ 4 files changed, 73 insertions(+), 3 deletions(-) create mode 100644 lib/v8/array.rb create mode 100644 lib/v8/object.rb diff --git a/lib/v8.rb b/lib/v8.rb index 04b89cf..2c5b65e 100644 --- a/lib/v8.rb +++ b/lib/v8.rb @@ -2,4 +2,6 @@ require "v8/version" require 'v8/init' require 'v8/conversion' -require 'v8/context' \ No newline at end of file +require 'v8/context' +require 'v8/object' +require 'v8/array' \ No newline at end of file diff --git a/lib/v8/array.rb b/lib/v8/array.rb new file mode 100644 index 0000000..fa84a31 --- /dev/null +++ b/lib/v8/array.rb @@ -0,0 +1,13 @@ +class V8::Array < V8::Object + def each + @context.enter do + for i in 0..(@native.Length() - 1) + yield @context.to_ruby(@native.Get(i)) + end + end + end + + def length + @native.Length() + end +end \ No newline at end of file diff --git a/lib/v8/conversion.rb b/lib/v8/conversion.rb index b6049dd..7c36f2a 100644 --- a/lib/v8/conversion.rb +++ b/lib/v8/conversion.rb @@ -4,14 +4,20 @@ module V8::Conversion end def to_v8(ruby_object) - ruby_object.respond_to?(:to_v8) ? ruby_object.to_v8 : case ruby_object - when Numeric then ruby_object + if ruby_object.respond_to?(:to_v8) + ruby_object.method(:to_v8).arity == 1 ? ruby_object.to_v8(self) : ruby_object.to_v8 else V8::C::Object::New() end end end +class Numeric + def to_v8 + self + end +end + class V8::C::String def to_ruby self.Utf8Value() @@ -36,3 +42,31 @@ class Time end end +class V8::C::Object + def to_ruby + V8::Object.new(self) + end +end + +class V8::Object + def to_v8 + self.native + end +end + +class V8::C::Array + def to_ruby + V8::Array.new(self) + end +end + +class Array + def to_v8(context) + array = V8::C::Array::New(length) + each_with_index do |item, i| + rputs "i: #{item}" + array.Set(i, context.to_v8(item)) + end + return array + end +end \ No newline at end of file diff --git a/lib/v8/object.rb b/lib/v8/object.rb new file mode 100644 index 0000000..3822fac --- /dev/null +++ b/lib/v8/object.rb @@ -0,0 +1,21 @@ +class V8::Object + attr_reader :native + + def initialize(native) + @native = native + @context = V8::Context.current + end + + def [](key) + @context.enter do + @context.to_ruby @native.Get(@context.to_v8(key)) + end + end + + def []=(key, value) + @context.enter do + @native.Set(@context.to_v8(key), @context.to_v8(value)) + end + return value + end +end \ No newline at end of file