Skip to content

Commit

Permalink
Use erb/escape for faster html escaping if available
Browse files Browse the repository at this point in the history
ERB::Escape#html_escape will return input strings as is without
allocating new strings if no escaping is needed, which can result
in better performance for such strings. This shouldn't cause any
issues in Erubi, because the result of Erubi.h is only used to
concat to an existing string.
  • Loading branch information
jeremyevans committed Dec 19, 2022
1 parent 5bbda87 commit 5938072
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 19 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG
@@ -1,5 +1,7 @@
=== master

* Use erb/escape for faster html escaping if available (jeremyevans)

* Default :freeze_template_literals option to false if running with --enable-frozen-string-literal (casperisfine) (#35)

=== 1.11.0 (2022-08-02)
Expand Down
43 changes: 24 additions & 19 deletions lib/erubi.rb
Expand Up @@ -18,30 +18,35 @@ module Erubi
# :nocov:

begin
require 'cgi/escape'
# :nocov:
unless CGI.respond_to?(:escapeHTML) # work around for JRuby 9.1
CGI = Object.new
CGI.extend(defined?(::CGI::Escape) ? ::CGI::Escape : ::CGI::Util)
end
# :nocov:
# Escape characters with their HTML/XML equivalents.
def self.h(value)
CGI.escapeHTML(value.to_s)
end
require 'erb/escape'
define_singleton_method(:h, ERB::Escape.instance_method(:html_escape))
rescue LoadError
# :nocov:
ESCAPE_TABLE = {'&' => '&amp;'.freeze, '<' => '&lt;'.freeze, '>' => '&gt;'.freeze, '"' => '&quot;'.freeze, "'" => '&#39;'.freeze}.freeze
if RUBY_VERSION >= '1.9'
def self.h(value)
value.to_s.gsub(/[&<>"']/, ESCAPE_TABLE)
begin
require 'cgi/escape'
# :nocov:
unless CGI.respond_to?(:escapeHTML) # work around for JRuby 9.1
CGI = Object.new
CGI.extend(defined?(::CGI::Escape) ? ::CGI::Escape : ::CGI::Util)
end
else
# :nocov:
# Escape characters with their HTML/XML equivalents.
def self.h(value)
value.to_s.gsub(/[&<>"']/){|s| ESCAPE_TABLE[s]}
CGI.escapeHTML(value.to_s)
end
rescue LoadError
# :nocov:
ESCAPE_TABLE = {'&' => '&amp;'.freeze, '<' => '&lt;'.freeze, '>' => '&gt;'.freeze, '"' => '&quot;'.freeze, "'" => '&#39;'.freeze}.freeze
if RUBY_VERSION >= '1.9'
def self.h(value)
value.to_s.gsub(/[&<>"']/, ESCAPE_TABLE)
end
else
def self.h(value)
value.to_s.gsub(/[&<>"']/){|s| ESCAPE_TABLE[s]}
end
end
# :nocov:
end
# :nocov:
end

class Engine
Expand Down

0 comments on commit 5938072

Please sign in to comment.