Skip to content

Instantly share code, notes, and snippets.

@chendo
Created July 10, 2018 03:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chendo/57b873c39fae0911a74c00b7610ecf21 to your computer and use it in GitHub Desktop.
Save chendo/57b873c39fae0911a74c00b7610ecf21 to your computer and use it in GitHub Desktop.
go_interactive lets you interactively write specs
class GoInteractive
def self.start(*args, **kwargs)
@init ||= begin
Pry.hooks.add_hook(:before_eval, "go_interactive") do |code, pry|
current.before_eval(code, pry)
end
Pry.hooks.add_hook(:after_eval, "go_interactive") do |result, pry|
current.after_eval(result, pry)
end
Pry::Commands.block_command("shipit", "Inserts successful interactive code back into the file") do
GoInteractive.current.ship_it
end
true
end
self.current = new
self.current.start(*args, **kwargs)
end
cattr_accessor :current
def initialize
@lines ||= []
end
def before_eval(code, pry)
@current_code = code
@exception = nil
end
def after_eval(result, pry)
if ex = $!
# Exception, ignore result
else
@lines << @current_code.strip unless @current_code.blank?
end
end
def ship_it
puts @lines.join("\n")
end
def start(caller_index: 0)
binding.of_caller(caller_index + 2).pry
end
end
# in a helper or whereever
def go_interactive
GoInteractive.start(caller_index: 1) # change caller_index so the correct binding is
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment