1
0
Fork 0
mirror of https://github.com/awesome-print/awesome_print synced 2023-03-27 23:22:34 -04:00

Fixed Array#grep, resolves #119

This commit is contained in:
Michael Dvorkin 2013-10-15 13:21:45 -07:00
parent 765042f7f1
commit 7161934b4d
2 changed files with 10 additions and 25 deletions

View file

@ -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

View file

@ -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)