-
Notifications
You must be signed in to change notification settings - Fork 9
/
RubyEval.py
80 lines (70 loc) · 2.51 KB
/
RubyEval.py
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
import subprocess
import sublime, sublime_plugin
class EvalAsRuby:
def ruby(self):
try:
return self.view.settings().get("ruby_eval").get("ruby")
except AttributeError:
return "ruby"
def eval_as_ruby(self, script):
proc = subprocess.Popen(self.ruby(),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
ruby_input = u"""
require 'stringio'
io = StringIO.new
begin
$stdout = $stderr = io
result = (lambda {
%s
}).call
ensure
$stdout = STDOUT
$stderr = STDERR
end
if io.string.empty?
case result
when String
print result
else
print result.inspect
end
else
print io.string
end
""" % script
output, error = proc.communicate(ruby_input.encode('utf-8'))
output = output.strip()
if proc.poll():
output += "\n" + error
try:
return str(output, 'utf-8')
except NameError:
return unicode(output ,encoding='utf-8')
class RubyEvalCommand(sublime_plugin.TextCommand, EvalAsRuby):
def run(self, edit, output_to_editor=True):
for region in self.view.sel():
if region.size() == 0:
# eval line
region_of_line = self.view.line(region)
script = self.view.substr(region_of_line)
output = self.eval_as_ruby(script)
if output_to_editor:
self.insert_output(output, region, edit, region_of_line.b, "\n")
else:
pass # TODO
else:
# eval selected
script = self.view.substr(region)
output = self.eval_as_ruby(script)
start = max(region.a, region.b)
space = "" if script[-1] == "\n" else " "
if output_to_editor:
self.insert_output(output, region, edit, start, space)
else:
pass # TODO
def insert_output(self, output, region, edit, start, space):
i = self.view.insert(edit, start, space + output)
self.view.sel().subtract(region)
self.view.sel().add(sublime.Region(start + len(space), start + i))