From f77a2ab5ca003fd3866b12118e3d85da7cd64de8 Mon Sep 17 00:00:00 2001 From: John Mair Date: Sun, 24 Jun 2012 01:48:11 +1200 Subject: [PATCH] added `before_eval` hook & tests This came about because KINGSABRI wanted his pry console to only execute commands, not ruby code (lol). I conconcated the following piece of code that achieves this, but it required a before_eval hook: ``` _pry_.hooks.add_hook(:before_eval, :kill_ruby) do |code, pry| if !code.empty? pry.suppress_output = true pry.output.puts "Command #{code.strip} not found, type 'help'" code.replace("") end end ``` --- lib/pry/pry_instance.rb | 4 ++++ test/test_hooks.rb | 31 +++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/lib/pry/pry_instance.rb b/lib/pry/pry_instance.rb index 7f999f97..53751d80 100644 --- a/lib/pry/pry_instance.rb +++ b/lib/pry/pry_instance.rb @@ -49,6 +49,8 @@ class Pry attr_accessor :extra_sticky_locals + attr_accessor :suppress_output + # This is exposed via Pry::Command#state. attr_reader :command_state @@ -268,6 +270,8 @@ class Pry code = r(target) + exec_hook :before_eval, code, self + result = target.eval(code, Pry.eval_path, Pry.current_line) set_last_result(result, target, code) diff --git a/test/test_hooks.rb b/test/test_hooks.rb index a86098cc..50814ae2 100644 --- a/test/test_hooks.rb +++ b/test/test_hooks.rb @@ -394,6 +394,37 @@ describe Pry::Hooks do Pry.config.exception_whitelist = old_ew end + describe "before_eval hook" do + describe "modifying input code" do + it 'should replace input code with code determined by hook' do + hooks = Pry::Hooks.new.add_hook(:before_eval, :quirk) { |code, pry| code.replace(":little_duck") } + redirect_pry_io(InputTester.new(":jemima", "exit-all"), out = StringIO.new) do + Pry.start(self, :hooks => hooks) + end + out.string.should =~ /little_duck/ + out.string.should.not =~ /jemima/ + end + + it 'should not interfere with command processing when replacing input code' do + commands = Pry::CommandSet.new do + import_from Pry::Commands, "exit-all" + + command "how-do-you-like-your-blue-eyed-boy-now-mister-death" do + output.puts "in hours of bitterness i imagine balls of sapphire, of metal" + end + end + + hooks = Pry::Hooks.new.add_hook(:before_eval, :quirk) { |code, pry| code.replace(":little_duck") } + redirect_pry_io(InputTester.new("how-do-you-like-your-blue-eyed-boy-now-mister-death", "exit-all"), out = StringIO.new) do + Pry.start(self, :hooks => hooks, :commands => commands) + end + out.string.should =~ /in hours of bitterness i imagine balls of sapphire, of metal/ + out.string.should.not =~ /little_duck/ + end + end + + end + describe "exceptions" do before do Pry.config.hooks.add_hook(:after_eval, :baddums){ raise "Baddums" }