Skip to content

Commit

Permalink
Expose Opal.bridge_class for bridging native prototypes
Browse files Browse the repository at this point in the history
  • Loading branch information
adambeynon committed Nov 2, 2013
1 parent 77e8175 commit 4bef9b3
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 3 deletions.
21 changes: 18 additions & 3 deletions corelib/runtime.js
Expand Up @@ -176,7 +176,11 @@

constructor.prototype.constructor = constructor;

// class itself
return boot_class_meta(superklass, constructor);
};

// class itself
function boot_class_meta(superklass, constructor) {
var mtor = function() {};
mtor.prototype = superklass.constructor.prototype;

Expand All @@ -198,7 +202,7 @@
constructor.prototype._klass = klass;

return klass;
};
}

// Define new module (or return existing module)
Opal.module = function(base, id) {
Expand Down Expand Up @@ -323,16 +327,26 @@
* @return [Class] returns new ruby class
*/
function bridge_class(name, constructor) {
var klass = boot_class(RubyObject, constructor);
var klass = boot_class_meta(RubyObject, constructor);

klass._name = name;

create_scope(Opal, klass, name);
bridged_classes.push(klass);

var object_methods = RubyBasicObject._methods.concat(RubyObject._methods);

for (var i = 0, len = object_methods.length; i < len; i++) {
var meth = object_methods[i];
constructor.prototype[meth] = RubyObject._proto[meth];
}

return klass;
};

// private method
Opal.bridge_class = bridge_class;

/*
* constant assign
*/
Expand Down Expand Up @@ -714,6 +728,7 @@
};

function define_basic_object_method(jsid, body) {
RubyBasicObject._methods.push(jsid);
for (var i = 0, len = bridged_classes.length; i < len; i++) {
bridged_classes[i]._proto[jsid] = body;
}
Expand Down
36 changes: 36 additions & 0 deletions spec/corelib/runtime/bridged_classes_spec.rb
@@ -1,6 +1,42 @@
require 'spec_helper'

%x{
var bridge_class_demo = function(){};
Opal.bridge_class('TopBridgedClassDemo', bridge_class_demo);
bridge_class_demo.prototype.$foo = function() { return "bar" };
}

describe "Bridged Classes" do
describe "Opal.bridge_class" do
before do
@bridged = ::TopBridgedClassDemo
@instance = `new bridge_class_demo`
end

it "should expose the given class at the top level scope" do
@bridged.should be_kind_of(Class)
end

it "gives the class the correct name" do
@bridged.name.should == "TopBridgedClassDemo"
end

it "should have all BasicObject methods defined" do
@instance.should respond_to(:instance_eval)
@bridged.new.should respond_to(:==)
end

it "should have all Object methods defined" do
@instance.should respond_to(:class)
@bridged.new.should respond_to(:singleton_class)
end

it "instances of class should be able to call native ruby methods" do
@instance.foo.should == "bar"
@bridged.new.foo.should == "bar"
end
end

describe ".instance_methdods" do
it "should report methods for class" do
Array.instance_methods.should include(:shift)
Expand Down

0 comments on commit 4bef9b3

Please sign in to comment.