2007-04-15 @ 16:41
Converting JavaScript to Ruby with RKelly
I’ve been working on a yet-to-be-released project called RKelly, which will parse JavaScript and return a parse tree suitable for passing to Ruby2Ruby. Ruby2Ruby will then give you back ruby code that you can eval.
I thought I would share a few examples of what I have working so far, and also write a bit about where I want to go.
I have most simple looping working. For example, a for loop:
1 2 3 4 5 6 7 8 9 |
require 'rkelly' require 'ruby2ruby' rkelly = RKelly.new puts RubyToRuby.new().process(rkelly.process(DATA.read)) __END__ for(var i = 0; i < 10; i++) { alert('hello world'); } |
Will produce:
You can even calculate the Fibonacci sequence:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
require 'rkelly' require 'ruby2ruby' rkelly = RKelly.new puts RubyToRuby.new().process(rkelly.process(DATA.read)) __END__ function fib(n) { var s = 0; if(n == 0) return(s); if(n == 1) { s += 1; return(s); } else { return(fib(n - 1) + fib(n - 2)); } } |
Which produces:
1 2 3 4 5 6 7 8 9 10 |
def fib(n) s = 0 return s if (n == 0) if (n == 1) then s = (s + 1) return s else return (fib((n - 1)) + fib((n - 2))) end end |
Why am I torturing myself like this? I want to add JavaScript support to Mechanize, and I think I can do that with RKelly. So far I have been able to use RKelly for simple DOM manipulation with a slightly modified copy of Mechanize. If you would like to see that in action, just find me at one of the Seattle Ruby Brigade meetings.
I’ve also added some simple object support, which you can see after the jump.