From 3335adc55f7f197f6be237d8221a5d16b4a560a2 Mon Sep 17 00:00:00 2001 From: Charles Lowell Date: Sun, 15 Nov 2009 22:46:24 -0500 Subject: [PATCH] add rdocs for native_object --- lib/rhino/context.rb | 7 ++++--- lib/rhino/native_object.rb | 35 ++++++++++++++++++++++++++++++++++- 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/lib/rhino/context.rb b/lib/rhino/context.rb index e0b008f..57fdd79 100644 --- a/lib/rhino/context.rb +++ b/lib/rhino/context.rb @@ -100,7 +100,7 @@ module Rhino end - class ContextFactory < J::ContextFactory #:nodoc: + class ContextFactory < J::ContextFactory # :nodoc: def observeInstructionCount(cxt, count) raise RunawayScriptError, "script exceeded allowable instruction count" if count > @limit @@ -112,7 +112,7 @@ module Rhino end - class RhinoError < StandardError #:nodoc: + class RhinoError < StandardError # :nodoc: def initialize(native) @native = native end @@ -126,5 +126,6 @@ module Rhino end end - class RunawayScriptError < StandardError; end #:nodoc: + class RunawayScriptError < StandardError # :nodoc: + end end \ No newline at end of file diff --git a/lib/rhino/native_object.rb b/lib/rhino/native_object.rb index 913db6e..76d9947 100644 --- a/lib/rhino/native_object.rb +++ b/lib/rhino/native_object.rb @@ -1,27 +1,59 @@ module Rhino + # Wraps a javascript object and makes its properties available from ruby. class NativeObject include Enumerable + + # The native java object wrapped by this NativeObject. This will generally + # be an instance of org.mozilla.javascript.Scriptable attr_reader :j - def initialize(j) + def initialize(j) # :nodoc: @j = j end + # get a property from this javascript object, where +k+ is a string or symbol + # corresponding to the property name + # e.g. + # jsobject = Context.open do |cxt| + # cxt.eval('({foo: 'bar', 'Take me to': 'a funky town'})') + # end + # + # jsobject[:foo] # => 'bar' + # jsobject['foo'] # => 'bar' + # jsobject['Take me to'] # => 'a funky town' def [](k) To.ruby @j.get(k.to_s, @j) end + # set a property on the javascript object, where +k+ is a string or symbol corresponding + # to the property name, and +v+ is the value to set. e.g. + # + # jsobject = eval_js "new Object()" + # jsobject['foo'] = 'bar' + # Context.open(:with => jsobject) do |cxt| + # cxt.eval('foo') # => 'bar' + # end + def []=(k,v) @j.put(k.to_s,@j,To.javascript(v)) end + # enumerate the key value pairs contained in this javascript object. e.g. + # + # eval_js("{foo: 'bar', baz: 'bang'}").each do |key,value| + # puts "#{key} -> #{value} " + # end + # + # outputs foo -> bar baz -> bang def each for id in @j.getAllIds() do yield id,@j.get(id,@j) end end + # Converts the native object to a hash. This isn't really a stretch since it's + # pretty much a hash in the first place. def to_h {}.tap do |h| each do |k,v| @@ -30,6 +62,7 @@ module Rhino end end + # Convert this javascript object into a json string. def to_json(*args) to_h.to_json(*args) end