public
Description: Mozilla JavaScript Engine (SpiderMonkey) bindings for Ruby
Clone URL: git://github.com/matthewd/ruby-mozjs.git
ruby-mozjs / interactive.rb
100644 81 lines (68 sloc) 1.651 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
require "spidermonkey"
require "readline"
# require "#{File.dirname(__FILE__)}/env/env"
 
def copy_history
  new_history = []
  until Readline::HISTORY.empty?
    new_history.push(Readline::HISTORY.pop)
  end
  new_history
end
 
def paste_history(old_history)
  until old_history.empty?
    Readline::HISTORY << old_history.pop
  end
end
 
class SpiderMonkey::Value
  
  def to_proc
    if typeof == "function"
      proc {|*args| self.call_function("call", self, *args) }
    else
      raise TypeError, "You cannot convert a #{typeof} to a proc"
    end
  end
  
  def method_missing(meth, *args)
    if val = meth.to_s.match(/^(.*)=$/)
      set_property(val[1], *args)
    elsif !args.empty?
      call_function(meth.to_s, *args)
    else
      get_property(meth.to_s)
    end
  end
  
  alias_method :[], :get_property
  alias_method :[]=, :set_property
  
end
 
CX = cx = SpiderMonkey::Context.new
 
global = cx.global
 
cx.global.function("print") {|x| puts x}
 
local_binding = binding
 
ruby_readline = []
 
loop do
  input = Readline.readline("js> ", true)
  break if input == "exit"
  if input == "ruby"
    js_readline = copy_history
    paste_history(ruby_readline)
    loop do
      input = Readline.readline("rb> ", true)
      break if input == "done"
      exit if input == "exit"
      begin
        puts "=> " + eval(input, local_binding).inspect
      rescue Object => e
        puts e.message
        puts e.backtrace
      end
    end
    ruby_readline = copy_history
    paste_history(js_readline)
    next
  end
  begin
    puts "=> " + cx.eval(input).inspect
  rescue Object => e
    puts e.message
    puts e.backtrace
  end
end