Skip to content

Commit

Permalink
Fix regression where only first backslash/apostrophe was escaped
Browse files Browse the repository at this point in the history
d152b2d broke pretty much all usage
of Erubi on websites because it only escapes the first backslash
or apostrophe in the text when escaping.  This removes the use
of String#[]= to handle escaping, moving to String#gsub! (or
gsub in the frozen case).
  • Loading branch information
jeremyevans committed Nov 12, 2020
1 parent ec1f639 commit c78f722
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 8 deletions.
2 changes: 0 additions & 2 deletions CHANGELOG
Expand Up @@ -6,8 +6,6 @@

* Support :literal_prefix and :literal_postfix options for how to output literal tags (e.g. <%% code %>) (jaredcwhite) (#26, #27)

* Reduce memory allocation during template parsing (fatkodima, jeremyevans) (#25)

=== 1.9.0 (2019-09-25)

* Change default :bufvar from 'String.new' to '::String.new' to work with BasicObject (jeremyevans)
Expand Down
10 changes: 4 additions & 6 deletions lib/erubi.rb
Expand Up @@ -179,12 +179,10 @@ def initialize(input, properties={})
# Add raw text to the template. Modifies argument if argument is mutable as a memory optimization.
def add_text(text)
if text && !text.empty?
include_slash = text.include?('\\')
include_apos = text.include?("'")
if include_slash || include_apos
text = text.dup if text.frozen?
text['\\'] = '\\\\' if include_slash
text["'"] = "\\'" if include_apos
if text.frozen?
text = text.gsub(/['\\]/, '\\\\\&')
else
text.gsub!(/['\\]/, '\\\\\&')
end
@src << " " << @bufvar << " << '" << text << TEXT_END
end
Expand Down
43 changes: 43 additions & 0 deletions test/test.rb
Expand Up @@ -121,6 +121,49 @@ def self.quux
END3
end

it "should escape all backslashes and apostrophes in text" do
list = ['&\'<>"2']
check_output(<<END1, <<END2, <<END3){}
<table>
<tbody>' ' \\ \\
<% i = 0
list.each_with_index do |item, i| %>
<tr>
<td><%= i+1 %></td>
<td><%== item %></td>
</tr>
<% end %>
</tbody>
</table>
<%== i+1 %>
END1
_buf = ::String.new; _buf << '<table>
<tbody>\\' \\' \\\\ \\\\
'; i = 0
list.each_with_index do |item, i|
_buf << ' <tr>
<td>'; _buf << ( i+1 ).to_s; _buf << '</td>
<td>'; _buf << ::Erubi.h(( item )); _buf << '</td>
</tr>
'; end
_buf << ' </tbody>
</table>
'; _buf << ::Erubi.h(( i+1 )); _buf << '
';
_buf.to_s
END2
<table>
<tbody>' ' \\ \\
<tr>
<td>1</td>
<td>&amp;&#39;&lt;&gt;&quot;2</td>
</tr>
</tbody>
</table>
1
END3
end

it "should strip only whitespace for <%, <%- and <%# tags" do
check_output(<<END1, <<END2, <<END3){}
<% 1 %>
Expand Down

0 comments on commit c78f722

Please sign in to comment.