Avoid explictly freezing literals strings when possible

Ref: https://github.com/jeremyevans/erubi/pull/33

If the template is compiled with `frozen_string_literals: true`,
then explicitly freezing string is slightly wasteful as it will be
compiled as `opt_str_freeze` instead of a simple `putobject`.

The former has to check wether `String#freeze` was redefined every
time, which while fast is useless extra work.
This commit is contained in:
Jean Boussier 2022-07-28 11:40:55 +02:00
parent 887dc9af6c
commit 476aeda794
3 changed files with 23 additions and 18 deletions

@ -53,7 +53,7 @@ PATH
actionview (7.1.0.alpha)
activesupport (= 7.1.0.alpha)
builder (~> 3.1)
erubi (~> 1.4)
erubi (~> 1.11)
rails-dom-testing (~> 2.0)
rails-html-sanitizer (~> 1.1, >= 1.2.0)
activejob (7.1.0.alpha)
@ -205,7 +205,7 @@ GEM
http_parser.rb (>= 0.6.0)
em-socksify (0.3.2)
eventmachine (>= 1.0.0.beta.4)
erubi (1.10.0)
erubi (1.11.0)
et-orbi (1.2.6)
tzinfo
event_emitter (0.2.6)

@ -36,7 +36,7 @@
s.add_dependency "activesupport", version
s.add_dependency "builder", "~> 3.1"
s.add_dependency "erubi", "~> 1.4"
s.add_dependency "erubi", "~> 1.11"
s.add_dependency "rails-html-sanitizer", "~> 1.1", ">= 1.2.0"
s.add_dependency "rails-dom-testing", "~> 2.0"

@ -18,6 +18,9 @@ def initialize(input, properties = {})
properties[:preamble] ||= ""
properties[:postamble] ||= "#{properties[:bufvar]}.to_s"
# Tell Eruby that whether template will be compiled with `frozen_string_literal: true`
properties[:freeze_template_literals] = !Template.frozen_string_literal
properties[:escapefunc] = ""
super
@ -30,11 +33,11 @@ def add_text(text)
if text == "\n"
@newline_pending += 1
else
src << bufvar << ".safe_append='"
src << "\n" * @newline_pending if @newline_pending > 0
src << text.gsub(/['\\]/, '\\\\\&')
src << "'.freeze;"
with_buffer do
src << ".safe_append='"
src << "\n" * @newline_pending if @newline_pending > 0
src << text.gsub(/['\\]/, '\\\\\&') << @text_end
end
@newline_pending = 0
end
end
@ -44,16 +47,18 @@ def add_text(text)
def add_expression(indicator, code)
flush_newline_if_pending(src)
if (indicator == "==") || @escape
src << bufvar << ".safe_expr_append="
else
src << bufvar << ".append="
end
with_buffer do
if (indicator == "==") || @escape
src << ".safe_expr_append="
else
src << ".append="
end
if BLOCK_EXPR.match?(code)
src << " " << code
else
src << "(" << code << ");"
if BLOCK_EXPR.match?(code)
src << " " << code
else
src << "(" << code << ")"
end
end
end
@ -69,7 +74,7 @@ def add_postamble(_)
def flush_newline_if_pending(src)
if @newline_pending > 0
src << bufvar << ".safe_append='#{"\n" * @newline_pending}'.freeze;"
with_buffer { src << ".safe_append='#{"\n" * @newline_pending}" << @text_end }
@newline_pending = 0
end
end