Question

If I have a javascript object, I would normally interact with the object and its methods like this:

var obj = someObject.getInstance();
var result = obj.someMethod();

where someMethod is defined like this:

someObject.prototype.someOtherMethod = function() { //do stuff };
someObject.prototype.someMethod = function(foo) { this.someOtherMethod(); };

However, I am getting an error when I want to call someMethod in Ruby via ExecJS:

context = ExecJS.compile(# the javascript file)
context.call('someObject.getInstance().someMethod') 
# Gives a TypeError where Object has no method 'someOtherMethod'

On the other hand, functions that are defined in the javascript module are working fine:

someFunction = function() { // do stuff };

# in Ruby
context.call('someFunction') # does stuff

Can ExecJS handle Javascript objects and their methods, or am I only able to call functions with it?

With regards to the specific application, I am looking into https://github.com/joenoon/libphonenumber-execjs, but the parse function in Libphonenumber does not work for the above reason.

Was it helpful?

Solution

Discovered the answer through some experimentation. I managed to get the desired functionality by using context.exec() instead of call.

js = <<JS
var jsObj = someObject.getInstance();
var res = jsObj.someMethod();
return res;
JS

context.exec(js);

However, if your method returns a Javascript object, you have to serialize it first or otherwise parse the results so that it can be returned by ExecJS into a suitable Ruby object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top