1
0
Fork 0
mirror of https://github.com/rubyjs/therubyrhino synced 2023-03-27 23:21:34 -04:00

add rdocs for native_object

This commit is contained in:
Charles Lowell 2009-11-15 22:46:24 -05:00
parent b5fb736cfd
commit 3335adc55f
2 changed files with 38 additions and 4 deletions

View file

@ -126,5 +126,6 @@ module Rhino
end end
end end
class RunawayScriptError < StandardError; end #:nodoc: class RunawayScriptError < StandardError # :nodoc:
end
end end

View file

@ -1,27 +1,59 @@
module Rhino module Rhino
# Wraps a javascript object and makes its properties available from ruby.
class NativeObject class NativeObject
include Enumerable include Enumerable
# The native java object wrapped by this NativeObject. This will generally
# be an instance of org.mozilla.javascript.Scriptable
attr_reader :j attr_reader :j
def initialize(j) def initialize(j) # :nodoc:
@j = j @j = j
end 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) def [](k)
To.ruby @j.get(k.to_s, @j) To.ruby @j.get(k.to_s, @j)
end 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) def []=(k,v)
@j.put(k.to_s,@j,To.javascript(v)) @j.put(k.to_s,@j,To.javascript(v))
end 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 def each
for id in @j.getAllIds() do for id in @j.getAllIds() do
yield id,@j.get(id,@j) yield id,@j.get(id,@j)
end end
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 def to_h
{}.tap do |h| {}.tap do |h|
each do |k,v| each do |k,v|
@ -30,6 +62,7 @@ module Rhino
end end
end end
# Convert this javascript object into a json string.
def to_json(*args) def to_json(*args)
to_h.to_json(*args) to_h.to_json(*args)
end end