codef0rmer codef0rmer - 4 months ago 7
Ruby Question

String#gsub messing up the replacement?

I'm trying to replace a part of a page with external content on the fly.

Here is the

source.html
:

<!DOCTYPE html>
<html>
<head>
<%= foobar %>
</head>
<body>
This is body
</body>
</html>


And a replacement string
inject.js
:

var REGEXP = /^\'$/i; var foo = 1;


A ruby code that outputs a file by combining both.

pageContent = File.read('./source.html')
jsContent = File.read('./inject.js');
output = pageContent.gsub("<%= foobar %>", jsContent)
File.open('./dest.html', "w+") do |f|
f.write(output)
end


However, I get the messed up
dest.html
which is happening because of
\'
in
inject.js
.

<!DOCTYPE html>
<html>
<head>
var REGEXP = /^
</head>
<body>
This is body
</body>
</html>$/i; var foo = 1;
</head>
<body>
This is body
</body>
</html>


How do I get rid of this issue?

Answer

Try using gsub block form:

output = pageContent.gsub("<%= foobar %>") { jsContent }