Is it possible to compile ruby to js in a way that the ruby functions could be used from javascript?

72 views
Skip to first unread message

Emiliano Heyns

unread,
Jul 22, 2014, 8:48:56 AM7/22/14
to opa...@googlegroups.com
In other words can I export functions/classes/objects and use them from javascript?

Elia Schito

unread,
Jul 22, 2014, 12:48:30 PM7/22/14
to opa...@googlegroups.com
Yes, you just need to be aware of the relation between Opal and JS.

At a basic level all Ruby constants are also stored under the Opal namespace, and all methods are stored as properties starting with a "$".
So if you want for example use an Hash from JS you can do the following:

var hash = Opal.Hash.$new()
hash['$[]=']('a', 1)
console.log(hash.$inspect()) // => "{:a => 1}"

Calling blocks is a bit more tricky, but can still be done from js:

var array = [1,2,3]
// _p stands for proc
array.$each_with_index._p = function(number, index){ console.log(number, index) }
array.$each_with_index.call(array)


Luckily there's also a helper for blocks:
Opal.block_send

var array = [1,2,3]
// _p stands for proc
Opal.block_send(array, 'each_with_index', function(number, index){ console.log(number, index) })


If you open a question on stackoverflow (tag #opalrb) I'll be happy to repost the answer there so that everyone can profit from it :)
On Tue, Jul 22, 2014 at 2:48 PM, Emiliano Heyns <emilian...@iris-advies.com> wrote:
In other words can I export functions/classes/objects and use them from javascript?

--
You received this message because you are subscribed to the Google Groups "opalrb" group.
To unsubscribe from this group and stop receiving emails from it, send an email to opalrb+un...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages