abhijit abhijit - 2 years ago 211
Ruby Question

Ruby gsub, NoMemoryError: failed to allocate memory.

We have a html template cached - which has placeholder values. Based on the real object values, the placeholders are being replaced. This works fine mostly but sometimes results in error(failed to allocate memory).

replacement_hash.keys.each do |placeholder|
value = ##some logic to get values from model using placeholder text.
text.gsub!(placeholder, value)

Any suggestions on how this can be fixed(made more efficient) or any alternate ways to do this?


Answer Source

This was due to bad user data - string containing invalid values - which resulted gsub to work incorrectly and same string which was to be replaced by gsub was inserted back again.

And code had a recursive function which will continue replacing things until no string with [[xxx]] is present - this caused the code to go into a loop until memory was full.

"Kiprosh [[signature]]".gsub("[[signature]]", "\0 and \0")
expected =>  "Kiprosh \0 and \0"
actual   => "Kiprosh [[signature]] and [[signature]]"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download