Skip to content

Commit

Permalink
Make Native method calls unwrap arguments and wrap results
Browse files Browse the repository at this point in the history
  • Loading branch information
meh committed Nov 5, 2013
1 parent 49ab70f commit 16af36e
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 4 deletions.
40 changes: 36 additions & 4 deletions corelib/native.rb
Expand Up @@ -181,18 +181,28 @@ def self.convert(value)
end

def self.call(obj, key, *args, &block)
args << block if block

%x{
var prop = #{obj}[#{key}];
if (prop == null) {
return nil;
}
else if (prop instanceof Function) {
var result = prop.apply(#{obj}, #{args});
if (block !== nil) {
args.push(block);
}
args = #{args.map {|value|
native = try_convert(value)
return result == null ? nil : result;
if nil === native
value
else
native
end
}};
return #{Native(`prop.apply(#{obj}, #{args})`)};
}
else if (#{native?(`prop`)}) {
return #{Native(`prop`)};
Expand All @@ -205,6 +215,10 @@ def self.call(obj, key, *args, &block)

include Base

def ==(other)
`#@native === #{Native.try_convert(other)}`
end

def has_key?(name)
`#@native.hasOwnProperty(#{name})`
end
Expand Down Expand Up @@ -264,6 +278,24 @@ def method_missing(mid, *args, &block)
def nil?
false
end

def is_a?(klass)
klass == Native
end

alias kind_of? is_a?

def instance_of?(klass)
klass == Native
end

def class
`self._klass`
end

def inspect
"#<Native:#{`String(#@native)`}>"
end
end

# native global
Expand Down
10 changes: 10 additions & 0 deletions spec/corelib/native/method_missing_spec.rb
Expand Up @@ -36,4 +36,14 @@
it "should pass the block as function" do
Native(`{ a: function(func) { return func(); } }`).a { 42 }.should == 42
end

it "should unwrap arguments" do
x = `{}`

Native(`{ a: function(a, b) { return a === b } }`).a(Native(x), x).should == true
end

it "should wrap result" do
Native(`{ a: function() { return {}; } }`).a.class.should == Native
end
end

0 comments on commit 16af36e

Please sign in to comment.