Replies: 5 comments
|
This is because bridging works with JavaScript classes (i.e. constructor functions), and even in that case the syntax would be: class Test < `window.constructor`
def foo; 123; end
end
win = `window`
win.foo # => 123In Ruby the only thing that you can extend are classes, and that holds true in Opal. I'm closing this to keep the issues tidy, but feel free to reach out in the slack channel o on stack overflow (tag opalrb) for more help on how to handle native objects and inheritance. |
|
PS. I didn't test the code above, consider it just demonstrative |
|
There are several issues. class MyWindow < Native(`window`)
def self.url
location.href
end
end
MyWindow.url # => "https://github.com/opal/opal/issues/2114"The main issue here is that As for class Test < `window.constructor`
def foo; 123; end
endThis does opposite, it changes original JS object, not creates a subclass and it works only for some objects. It doesn't work for > Object.setPrototypeOf(window.constructor.prototype, Object.create(null))
Uncaught TypeError: can't set prototype of this objectAlso I find this syntax to be very counterintuitive. I don't see why Opal couldn't have used more straightforward way of class `Window`
def foo; 123; end
endwhich makes a lot more sense and is clearer/readable. |
For this use case I think the best approach would be changing the singleton class of the Native wrapper: $window = Native(`window`)
class << $window
def self.url
location.href
end
end
I agree with this, using the subclass syntax for bridging is not the best option, the problem with using the backticks directly is that class Number < Numeric
Opal.bridge(`Number`, self)
...
endwhat do you think? |
$window = Native(`window`)
class << $window
def self.url
location.href
end
endHadn't thought about this and it actually works but there is downside. class Number < Numeric
Opal.bridge(`Number`, self)
...
endThis is definitely better but I think removing support for current way is not really realistic because of already existing code which does it that way. |
Uh oh!
There was an error while loading. Please reload this page.
This fails with
It happens in Opal.bridge https://github.com/opal/opal/blob/master/opal/corelib/runtime.js#L1223
All reactions