Convert Ruby to JavaScript
This is old! You should also check out RubyJS for a fuller implementation of the same idea.
I knocked together this simple proof-of-concept Ruby-to-JavaScript converter in a few hours today. It seems somehow wrong, like grafting a pretty girl’s head onto a donkey, but I’ve done it anyway! It converts Ruby code like this:
class Demo def initialize @clicks = 0 3.times{ self.puts('Hello! I am a Ruby script!') } end def puts(str) document.getElementById('debug')['innerHTML'] = document.getElementById('debug')['innerHTML'] + str + "\n" end def clicked @clicks += 1 self.puts("Click number " + @clicks.to_s) end end
into JavaScript code like this:
function Demo(){ self=this; self.instanceVariables={}; self.instanceVariables['@clicks']=Number(0); Number(3).times(function(){ self.puts("Hello! I am a Ruby script!") }) } Demo.prototype = { puts: function(str){ self=this; document.getElementById("debug")["innerHTML"]= document.getElementById("debug")["innerHTML"]+str+"\n" }, clicked: function(){ self=this; self.instanceVariables['@clicks']= self.instanceVariables['@clicks']+Number(1); self.puts("Click number "+ self.instanceVariables['@clicks'].toString()) } }
It uses Ryan Davis et al’s ParseTree and Florian Groß’s ruby.js for most of the hard work. It’s still very limited, and there are many warts, not least of which is the requirement for an explicit receiver on every method. Nonetheless, I think it’s going to be useful.
Interested? Download it and try it for yourself.
Update
There’s now a project page on RubyForge.