Monday, June 16, 2008

javascript ruby interpreter -- johnson

require 'johnson'

puts Johnson.evaluate("4 + 4") # => 8
puts Johnson.evaluate("4 + foo", :foo => 4) # => 8

js_function_test = "foo = function (bar) { return parseInt(bar); };"
puts Johnson.parse(js_function_test)
puts Johnson.parse("alert(33)")

ctx = Johnson::Runtime.new
ctx['alert'] = lambda { |x| puts x }
puts ctx.evaluate('alert("Hello world!");')


j = Johnson::Runtime.new

# Introduce a new JavaScript function, named print,
# which calls a Ruby function
# j.print = lambda {|msg| puts msg}; # => undefined method `print=' for #<Johnson::Runtime:0x4e8c70>
j[:print] = lambda {|msg| puts msg};

# Add in a new pure-JavaScript function which calls
# our previously-introduced print function
j.evaluate("function alert(msg){ print('Alert:' + msg); }");

# Prints out 'Alert: text'
j.evaluate("alert('text');");

class Monkey
def eat
puts "Nom, nom, nom, bananas!"
end
end

j = Johnson::Runtime.new

# toss a monkey into the runtime
m = Monkey.new
j[:m] = m

# add a JSland function to our monkey...
j.evaluate("m.chow = function() { this.eat() }")

# ...and now it's available as an instance method on our native Ruby object!
m.chow

No comments :