Created
April 6, 2016 03:06
-
-
Save topher6345/0fec21d0d64c1b7c8dabd347ce6f1757 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import subprocess | |
import sublime, sublime_plugin | |
import re | |
class EvalAsRuby: | |
# Method to run Ruby from the shell | |
def ruby(self): | |
try: | |
# Example: | |
# "sno_phort": | |
# { | |
# "ruby": "~/.rvm/rubies/ruby-2.3.0-preview1/bin/ruby" | |
# }, | |
return self.view.settings().get("sno_phort").get("ruby") | |
except AttributeError: | |
return "ruby" | |
def eval_as_ruby(self, script): | |
# Open Subprocess | |
proc = subprocess.Popen([self.ruby()], | |
stdout=subprocess.PIPE, | |
stderr=subprocess.PIPE, | |
stdin=subprocess.PIPE) | |
# Context to run Ruby Code | |
ruby_input = """ | |
# YAY Ruby Code | |
# | |
# | |
require 'rubygems' | |
gem 'activesupport' | |
require 'active_support' | |
require 'active_support/core_ext' | |
require 'stringio' | |
require 'json' | |
require 'yaml' | |
require 'did_you_mean' if RUBY_VERSION == '2.3.0' | |
require 'did_you_mean' if RUBY_VERSION != '2.3.0' | |
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 | |
puts result | |
else | |
puts result.inspect | |
end | |
else | |
puts io.string | |
end | |
""" % script | |
output, error = proc.communicate(ruby_input.encode('utf-8')) | |
output = output.strip() | |
if proc.poll(): | |
output += error | |
try: | |
return str(output, 'utf-8') | |
except NameError: | |
return unicode(output ,encoding='utf-8') | |
class SnoPhortCommand(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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment