evfwcqcg
evfwcqcg

Reputation: 16335

Strange behavior with html_escape

I was writing the helper for my rails app, which should make some manupulations with string, and when I found this. If I use gsub method exactly after escaping, then this code doesn't work like I wanted to (it doesn't find the number 999).

require 'active_support/core_ext/string'

text = ">999"

text = ERB::Util.html_escape(text)

# text = text.downcase
text.gsub!(/\&gt\;(\d+)/) { "found [#{$1}]" }

puts text

In another case, if I uncomment text = text.downcase, i.e. apply any method to string, then all works fine. So what should I do if I would like to use gsub exactly after html_escape method?

Upvotes: 2

Views: 119

Answers (1)

Daniel Pittman
Daniel Pittman

Reputation: 17182

You are hitting an awesome feature; try this:

# ...as before.
text = ERB::Util.html_escape(text)
puts text.class

text is actually an instance of ActiveSupport::SafeBuffer, which presumably implements the gsub! method, takes a block, but gets it somehow wrong - in that it doesn't result in $1 being set.

You can work around this by way of either:

text = text.to_s.gsub!(...)
text = text.gsub!(...) {|match| "found [#{match}]" }

You might find this inconsistency fixed in a later version of the ActiveSupport code, but otherwise you might as well file the bug report now; that gsub! behaviour is well documented and should be preserved.

Upvotes: 3

Related Questions