Skip to content

Instantly share code, notes, and snippets.

@thedayisntgray
Last active October 28, 2024 07:39
Show Gist options
  • Select an option

  • Save thedayisntgray/78d5444631a3f2a775fefd01dc769e1b to your computer and use it in GitHub Desktop.

Select an option

Save thedayisntgray/78d5444631a3f2a775fefd01dc769e1b to your computer and use it in GitHub Desktop.
from IPython.core.magic import register_cell_magic
import subprocess
import os
import re
from sys import stderr
import shutil
import atexit
class RubySession:
def __init__(self):
"""Initialize the Ruby session and ensure Ruby is installed."""
self.code_history = []
# Install Ruby if not present
try:
subprocess.run(['which', 'ruby'], check=True, capture_output=True)
print("Ruby is already installed")
except subprocess.CalledProcessError:
print("Ruby is not installed, attempting to install...")
if shutil.which('apt-get'):
subprocess.run(['apt-get', 'update', '-y'], check=True)
subprocess.run(['apt-get', 'install', '-y', 'ruby-full'], check=True)
print("Ruby installation complete")
else:
print("Error: Cannot install Ruby automatically. Please install Ruby manually.")
raise EnvironmentError("Ruby not found and automatic installation failed.")
def is_definition(self, code):
"""Check if the code contains definitions to be stored."""
return bool(re.match(r'\s*(\w+\s*=|def\s|class\s)', code))
def execute(self, code):
"""Execute Ruby code within the session."""
try:
# Combine code history with new code using str.format()
full_code = """
begin
# Previous code
{}
# New code
{}
rescue => e
puts "Error: #{{e.class}} - #{{e.message}}"
puts e.backtrace
end
""".format('\n '.join(self.code_history), code)
# Execute the code directly
result = subprocess.run(['ruby'],
input=full_code,
capture_output=True,
text=True)
# If execution was successful and code contains definitions, add to history
if result.returncode == 0 and self.is_definition(code):
self.code_history.append(code)
return result.stdout, result.stderr
except subprocess.CalledProcessError as e:
return '', f"Subprocess error: {e}"
except Exception as e:
return '', f"Unexpected error: {e}"
def cleanup(self):
"""Clean up temporary files."""
pass # No files to clean up since we're not writing to disk
def reset(self):
"""Reset the session by clearing code history."""
self.code_history = []
# Create global session
ruby_session = RubySession()
@register_cell_magic
def ruby(line, cell):
if 'reset' in line:
ruby_session.reset()
print("Ruby session reset")
return
try:
stdout, stderr_content = ruby_session.execute(cell)
if stdout:
print(stdout, end='')
elif not stderr_content:
print("Code executed successfully with no output.")
if stderr_content:
print(stderr_content, file=stderr, end='')
except Exception as e:
print(f"Error executing Ruby code: {e}", file=stderr)
# Register magic function and cleanup
get_ipython().register_magic_function(ruby, magic_kind='cell')
atexit.register(ruby_session.cleanup)
# User instructions
print("Ruby magic command ready! Use %%ruby to run Ruby code.")
print("Example:")
print("%%ruby")
print("puts 'Hello from Ruby!'")
print("\nTo reset the Ruby session, use:")
print("%%ruby reset")
print("Note: Be cautious when executing code that modifies the session state.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment