Class: MimickIRB

Inherits:
RubyLex
  • Object
show all
Defined in:
lib/wxirb.rb

Overview

This class is stolen almost verbatim from why_the_lucky_stiff’s Shoes example. (github.com/why/shoes/blob/master/samples/expert-irb.rb) He gets all the credit.

Defined Under Namespace

Classes: Continue, Empty

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(bind = TOPLEVEL_BINDING) ⇒ MimickIRB

Returns a new instance of MimickIRB.



24
25
26
27
28
# File 'lib/wxirb.rb', line 24

def initialize(bind=TOPLEVEL_BINDING)
  set_binding(bind)
  super()
  set_input(StringIO.new)
end

Instance Attribute Details

#startedObject

Returns the value of attribute started.



19
20
21
# File 'lib/wxirb.rb', line 19

def started
  @started
end

Instance Method Details

#run(str) ⇒ Object



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
81
# File 'lib/wxirb.rb', line 42

def run(str)
  obj = nil
  @io << str
  @io.rewind
  unless l = lex
    raise Empty if @line == ''
  else
    case l.strip
    when "reset"
      @line = ""
    else
      @line << l << "\n"
      if @ltype or @continue or @indent > 0
        raise Continue
      end
    end
  end
  unless @line.empty?
    obj = eval @line, @bind, "(irb)", @line_no
  end
  @line_no += @line.scan(/\n/).length
  @line = ''
  @exp_line_no = @line_no
 
  @indent = 0
  @indent_stack = []
 
  $stdout.rewind
  output = $stdout.read
  $stdout.truncate(0)
  $stdout.rewind
  [output, obj]
rescue Object => e
  case e when Empty, Continue
  else @line = ""
  end
  raise e
ensure
  set_input(StringIO.new)
end

#set_binding(bind) ⇒ Object Also known as: change_binding, cb



30
31
32
33
34
35
36
# File 'lib/wxirb.rb', line 30

def set_binding(bind)
  if bind.is_a? Binding
    @bind = bind
  else
    @bind = bind.instance_eval { binding }
  end
end