From 7161934b4d46d28860fa5eddf364b2ff6b92d1ea Mon Sep 17 00:00:00 2001 From: Michael Dvorkin Date: Tue, 15 Oct 2013 13:21:45 -0700 Subject: [PATCH] Fixed Array#grep, resolves #119 --- lib/awesome_print/core_ext/array.rb | 28 +++------------------------- spec/misc_spec.rb | 7 +++++++ 2 files changed, 10 insertions(+), 25 deletions(-) diff --git a/lib/awesome_print/core_ext/array.rb b/lib/awesome_print/core_ext/array.rb index ec1a1cd..634384d 100644 --- a/lib/awesome_print/core_ext/array.rb +++ b/lib/awesome_print/core_ext/array.rb @@ -27,33 +27,11 @@ class Array #:nodoc: end # # Intercepting Array#grep needs a special treatment since grep accepts - # an optional block. + # an optional block. For more info check out + # http://www.justskins.com/forums/bug-when-rerouting-string-52852.html # alias :original_grep :grep def grep(pattern, &blk) - # - # The following looks rather insane and I've sent numerous hours trying - # to figure it out. The problem is that if grep gets called with the - # block, for example: - # - # [].methods.grep(/(.+?)_by/) { $1.to_sym } - # - # ...then simple: - # - # original_grep(pattern, &blk) - # - # doesn't set $1 within the grep block which causes nil.to_sym failure. - # The workaround below has been tested with Ruby 1.8.7/Rails 2.3.8 and - # Ruby 1.9.2/Rails 3.0.0. For more info see the following thread dating - # back to 2003 when Ruby 1.8.0 was as fresh off the grill as Ruby 1.9.2 - # is in 2010 :-) - # - # http://www.justskins.com/forums/bug-when-rerouting-string-52852.html - # - # BTW, if you figure out a better way of intercepting Array#grep please - # let me know: twitter.com/mid -- or just say hi so I know you've read - # the comment :-) - # arr = unless blk original_grep(pattern) else @@ -68,7 +46,7 @@ class Array #:nodoc: # # [ 0, 1, 2, 3, 4 ].grep(1..2, &:succ) # - eval("%Q/#{match.to_s.gsub('/', '\/')}/ =~ #{pattern.inspect}", blk.binding) rescue ArgumentError + eval("%Q/#{match.to_s.gsub(/([^\\]?)\//, '\\1\/')}/ =~ #{pattern.inspect}", blk.binding) rescue ArgumentError yield match end end diff --git a/spec/misc_spec.rb b/spec/misc_spec.rb index 53f4a35..82f752b 100644 --- a/spec/misc_spec.rb +++ b/spec/misc_spec.rb @@ -39,6 +39,13 @@ describe "AwesomePrint" do grepped.ai(:plain => true, :multiline => false).should == '[ 2, 3, 4, 5 ]' end + # See https://github.com/michaeldv/awesome_print/issues/119 + it "properly escape slashes" do + hash = { :a => "http:\\/\\/" } + grepped = [ hash ].grep(Hash) { |x| true } + grepped.ai(:plain => true, :multiline => false).should == "[ true ]" + end + it "returns value passed as a parameter" do object = rand $stdout.stub(:puts)