Class: Rhino::NativeObject
- Includes:
- Enumerable
- Defined in:
- lib/rhino/native_object.rb
Overview
Wraps a javascript object and makes its properties available from ruby.
Direct Known Subclasses
Instance Attribute Summary collapse
-
#j ⇒ Object
readonly
The native java object wrapped by this NativeObject.
Instance Method Summary collapse
-
#[](k) ⇒ Object
get a property from this javascript object, where
k
is a string or symbol corresponding to the property name e.g. -
#[]=(k, v) ⇒ Object
set a property on the javascript object, where
k
is a string or symbol corresponding to the property name, andv
is the value to set. -
#each ⇒ Object
enumerate the key value pairs contained in this javascript object.
-
#initialize(j = nil) ⇒ NativeObject
constructor
:nodoc:.
-
#to_h ⇒ Object
Converts the native object to a hash.
-
#to_json(*args) ⇒ Object
Convert this javascript object into a json string.
Constructor Details
#initialize(j = nil) ⇒ NativeObject
:nodoc:
11 12 13 |
# File 'lib/rhino/native_object.rb', line 11 def initialize(j=nil) # :nodoc: @j = j || J::NativeObject.new end |
Instance Attribute Details
#j ⇒ Object (readonly)
The native java object wrapped by this NativeObject. This will generally be an instance of org.mozilla.javascript.Scriptable
9 10 11 |
# File 'lib/rhino/native_object.rb', line 9 def j @j end |
Instance Method Details
#[](k) ⇒ Object
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'
25 26 27 |
# File 'lib/rhino/native_object.rb', line 25 def [](k) To.ruby J::ScriptableObject.getProperty(@j,k.to_s) end |
#[]=(k, v) ⇒ Object
38 39 40 |
# File 'lib/rhino/native_object.rb', line 38 def []=(k,v) J::ScriptableObject.putProperty(@j, k.to_s, To.javascript(v)) end |
#each ⇒ Object
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
49 50 51 52 53 |
# File 'lib/rhino/native_object.rb', line 49 def each for id in @j.getAllIds() do yield id,@j.get(id,@j) end end |
#to_h ⇒ Object
Converts the native object to a hash. This isn’t really a stretch since it’s pretty much a hash in the first place.
57 58 59 60 61 62 63 64 |
# File 'lib/rhino/native_object.rb', line 57 def to_h {}.tap do |h| each do |k,v| v = To.ruby(v) h[k] = self.class === v ? v.to_h : v end end end |
#to_json(*args) ⇒ Object
Convert this javascript object into a json string.
67 68 69 |
# File 'lib/rhino/native_object.rb', line 67 def to_json(*args) to_h.to_json(*args) end |