Strange 'string modified' error!

Hi,

Got this strange error message coming from the second instance of the
‘scan’ method (line 39) on the text string. Any clues. Really stumped
me… It was working fine, then suddenly - boom it stopped.

...

text.scan(/\/\.asset\.[0-9]*\.url\./) do |url|
  id = url.gsub(/[^0-9]/,'').to_i
  if asset = Asset.find(id)
    text.gsub!(url, '/' + asset.url_for_link)
  end
end

39 text.scan(/.asset.[0-9]*.title./) do |url|
id = url.gsub(/[^0-9]/,’’).to_i
if asset = Asset.find(id)
text.gsub!(url, CGI.escapeHTML(asset.title))
end
end

...

The error is (in summary):

RuntimeError in SiteController#show_page

string modified

RAILS_ROOT: /var/www/downing/current/config/…

Application Trace

#{RAILS_ROOT}/app/filters/xhtml/xhtml_filter.rb:39:in `scan’

Many thanks in advance.

Best,

~ Mark D.

In the end I fixed it. I initially replaced the ‘scan’ with ‘gsub!’ as
the ‘text’ string was being changed inside the block passed to ‘scan’
which was causing the ‘string modified’ error.

However, even with ‘gsub!’ I was receving the same error. This seems to
be becuase the multiple ‘gsub!’ invocations are not thread safe? In the
end I had to use a mutex:

require ‘thread’
mutex = Mutex.new

mutex.synchronize do
text.gsub!(//.asset.([0-9]*).url./) { ‘/’ +
Asset.find($1).url_for_link }
end

mutex.synchronize do
text.gsub!(/.asset.([0-9]*).title./) {
CGI.escapeHTML(Asset.find($1).title) }
end

Not sure if this is actually the best solution, but it does work now!

~ Mark D.