SafeBuffer gsub broken

141 views
Skip to first unread message

Andrew Kaspick

unread,
Aug 13, 2011, 1:42:29 PM8/13/11
to Ruby on Rails: Core
Hello,

I've run into a bug with the implementation of gsub in
https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/string/output_safety.rb

My code is essentially this... (my pattern captures values to the
global variables $1, $2)

text.gsub(pattern) do |match|
# uses match, $1, $2
end

When running this, my match var is passed correctly, but $1 and $2 are
nil. If I remove gsub from the list of UNSAFE_STRING_METHODS gsub
works as expected, so gsub is currently broken in Rails as far as I
can see.

To test this you can do the following (do this in Rails 3-1... Rails
3-0 gsub is broken even more right now)...

Broken (using SafeBuffer)...
ruby-1.9.2-p290 :001 > ActiveSupport::SafeBuffer.new("capture
this").gsub(/(capture) (this)/){|match| p match, $1, $2}
"capture this"
nil
nil

Good (using String)...
ruby-1.9.2-p290 :004 > String.new("capture this").gsub(/(capture)
(this)/){|match| p match, $1, $2}
"capture this"
"capture"
"this"

Basically the current code doesn't persist the values of the globals
$1, $2, etc.

def #{unsafe_method}(*args, &block) # def gsub(*args, &block)
to_str.#{unsafe_method}(*args, &block)
end

I did some testing to rewrite this method and $1 and $2 are in fact
set in the overridden method, but they are nil inside the block of the
method outside of the override. The actual fix for this is somewhat
beyond my knowledge of ruby, as I thought global variables would
remain global, but something else is going on here. I read that some
of the special global vars are in fact treated as locals, so I'm not
sure if this is the case here.

Any ideas on how to fix this properly? Suggestions welcome so I can
submit a patch.

Andrew

Guillermo Iguaran

unread,
Aug 13, 2011, 1:46:21 PM8/13/11
to rubyonra...@googlegroups.com
There is a discussion about SaffeBuffer#gsub in https://github.com/rails/rails/issues/1555

-- 
Guillermo Iguaran
Sent with Sparrow
--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Core" group.
To post to this group, send email to rubyonra...@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-co...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-core?hl=en.

Andrew Kaspick

unread,
Aug 13, 2011, 1:51:02 PM8/13/11
to rubyonra...@googlegroups.com
Ah, thanks. Glad to see it's being worked on. I should have searched
the issues first.

I'll use my work around of using String.new(text) to force the
standard gsub usage.

Thanks again

Reply all
Reply to author
Forward
0 new messages