2009-10-06 09:52:45 -04:00
|
|
|
|
|
|
|
module Rhino
|
2009-11-15 22:46:24 -05:00
|
|
|
# Wraps a javascript object and makes its properties available from ruby.
|
2009-10-06 09:52:45 -04:00
|
|
|
class NativeObject
|
2009-10-06 10:04:57 -04:00
|
|
|
include Enumerable
|
2009-11-15 22:46:24 -05:00
|
|
|
|
|
|
|
# The native java object wrapped by this NativeObject. This will generally
|
|
|
|
# be an instance of org.mozilla.javascript.Scriptable
|
2009-10-06 09:52:45 -04:00
|
|
|
attr_reader :j
|
2009-10-06 10:04:57 -04:00
|
|
|
|
2009-11-15 22:46:24 -05:00
|
|
|
def initialize(j) # :nodoc:
|
2009-10-06 09:52:45 -04:00
|
|
|
@j = j
|
|
|
|
end
|
|
|
|
|
2009-11-15 22:46:24 -05:00
|
|
|
# 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'
|
2009-10-06 09:52:45 -04:00
|
|
|
def [](k)
|
2009-11-20 09:27:24 -05:00
|
|
|
To.ruby J::ScriptableObject.getProperty(@j,k.to_s)
|
2009-10-06 09:52:45 -04:00
|
|
|
end
|
|
|
|
|
2009-11-15 22:46:24 -05:00
|
|
|
# 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
|
|
|
|
|
2009-10-06 09:52:45 -04:00
|
|
|
def []=(k,v)
|
2009-11-20 09:27:24 -05:00
|
|
|
#@j.put(k.to_s,@j,To.javascript(v))
|
|
|
|
J::ScriptableObject.putProperty(@j, k.to_s, To.javascript(v))
|
2009-10-06 09:52:45 -04:00
|
|
|
end
|
2009-10-06 10:04:57 -04:00
|
|
|
|
2009-11-15 22:46:24 -05:00
|
|
|
# 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
|
2009-10-06 10:04:57 -04:00
|
|
|
def each
|
|
|
|
for id in @j.getAllIds() do
|
|
|
|
yield id,@j.get(id,@j)
|
|
|
|
end
|
|
|
|
end
|
2009-11-08 23:25:25 -05:00
|
|
|
|
2009-11-15 22:46:24 -05:00
|
|
|
# Converts the native object to a hash. This isn't really a stretch since it's
|
|
|
|
# pretty much a hash in the first place.
|
2009-11-08 23:25:25 -05:00
|
|
|
def to_h
|
|
|
|
{}.tap do |h|
|
|
|
|
each do |k,v|
|
|
|
|
h[k] = self.class === v ? v.to_h : v
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2009-11-15 22:46:24 -05:00
|
|
|
# Convert this javascript object into a json string.
|
2009-11-08 23:25:25 -05:00
|
|
|
def to_json(*args)
|
|
|
|
to_h.to_json(*args)
|
|
|
|
end
|
2009-10-06 09:52:45 -04:00
|
|
|
end
|
|
|
|
end
|