Class: Boxcars::RubyREPL

Inherits:
Object
  • Object
show all
Defined in:
lib/boxcars/ruby_repl.rb

Overview

used by Boxcars to run ruby code

Instance Method Summary collapse

Instance Method Details

#call(code:) ⇒ Object

Execute ruby code

Parameters:

  • code (String)

    The code to run



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/boxcars/ruby_repl.rb', line 8

def call(code:)
  Boxcars.debug "RubyREPL: #{code}", :yellow

  # wrap the code in an exception block so we can catch errors
  wrapped = "begin\n#{code}\nrescue Exception => e\n  puts 'Error: ' + e.message\nend"
  output = ""
  IO.popen("ruby", "r+") do |io|
    io.puts wrapped
    io.close_write
    output = io.read
  end
  if output =~ /^Error: /
    Boxcars.debug output, :red
    Result.from_error(output, code: code)
  elsif output.blank?
    Result.from_error("The code you gave me did not print a result", code: code)
  else
    output = ::Regexp.last_match(1) if output =~ /^\s*Answer:\s*(.*)$/m
    Boxcars.debug "Answer: #{output}", :yellow, style: :bold
    Result.from_text(output, code: code)
  end
end

#run(command) ⇒ Object

Execute ruby code

Parameters:

  • command (String)

    The code to run



33
34
35
# File 'lib/boxcars/ruby_repl.rb', line 33

def run(command)
  call(code: command)
end