source: Dev/trunk/d3/lib/env-js/envjs/rubyracer.rb @ 76

Last change on this file since 76 was 76, checked in by fpvanagthoven, 14 years ago

d3

File size: 2.5 KB
Line 
1require 'v8'
2require 'net/http'
3require 'uri'
4require 'thread'
5
6include Config
7
8lock  = Mutex.new
9class Runtime
10  def new_context()
11    V8::Context.new
12  end
13  def configure_context(runtime, context)
14    ruby = {}
15    Module.included_modules.each{|m|
16      #puts "adding module #{m}"
17      ruby[m.to_s] = m
18    }
19    Module.constants.each{|c|
20      #puts "adding constant #{c}"
21      ruby[c.to_s] = Kernel.eval(c)
22    }
23    Kernel.global_variables.each{|g|
24      #puts "adding global variable #{g}"
25      ruby[g.to_s] = Kernel.eval(g)
26    }
27    Kernel.methods.each{|m|
28      #puts "adding global method #{m}"
29      ruby[m.to_s] = Kernel.method(m)
30    }
31    ruby['CONFIG'] = CONFIG
32    ruby['gc'] = lambda{ GC.start() }
33    context['Ruby']  = ruby
34   
35    context['__this__']  = context
36    context['File']      = File
37    #context['sync']      = lambda{|fn| Proc.new{|*args|lock.synchronize {fn.call(*args)}} }
38    context['sync']      = lambda{|fn| Proc.new{|*args| fn.call(*args) }}
39    #context['spawn']     = lambda{|fn| Thread.new {fn.call}}
40    context['spawn']     = lambda{|fn| fn.call}
41    context['print']     = lambda{|msg| puts msg}
42    context['fopen']     = lambda{|name, mode| File.open(name, mode)}
43    context['runtime']   = runtime
44    context['new_context']   = lambda{
45      rt = Runtime.new
46      ct = rt.new_context()
47      rt.configure_context(rt, ct)
48      ct['_eval'] = lambda{|script| ct.eval(script)}
49      ct.eval('var t = new Function(); t._eval = __this__._eval;t;')
50    }
51    context['HTTPConnection'] = HTTPConnection.new
52  end
53end
54
55class HTTPConnection
56  def connect(host, port)
57    Net::HTTP.start(host, port)
58  end
59  def request(httpMethod, path)
60    case httpMethod
61    when "GET" then return Net::HTTP::Get.new(path)
62    when "PUT" then return Net::HTTP::Put.new(path)
63    when "POST" then return Net::HTTP::Post.new(path)
64    when "HEAD" then return Net::HTTP::Head.new(path)
65    when "DELETE" then return Net::HTTP::Delete.new(path)
66    else return nil
67    end
68  end
69  def go(connection, request, headers, data)
70    headers.each{|key,value| request.add_field(key,value)}
71    response, body = connection.request(request, data)
72    respheaders = Hash.new
73    response.each_header do |name, value|
74      respheaders.store(name, value)
75    end
76    response['body'] = body
77    [response, respheaders]
78  end
79  def finish(connection)
80    connection.finish if connection.started?
81  end
82end
83
84runtime = Runtime.new
85global = runtime.new_context()
86runtime.configure_context(runtime, global)
87envjs = ARGV[0]
88global.load(envjs)
89
90
Note: See TracBrowser for help on using the repository browser.