SafeBuffer gsub broken

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

There is a discussion about SaffeBuffer#gsub in https://github.com/rails/rails/issues/1555

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