lib/erubi.rb in erubi-1.1.0 vs lib/erubi.rb in erubi-1.2.0

- old
+ new

@@ -5,29 +5,31 @@ RANGE_ALL = 0..-1 if RUBY_VERSION >= '1.9' RANGE_FIRST = 0 RANGE_LAST = -1 + TEXT_END = "'.freeze;" # Escape the following characters with their HTML/XML # equivalents. def self.h(value) value.to_s.gsub(/[&<>"']/, ESCAPE_TABLE) end else # :nocov: RANGE_FIRST = 0..0 RANGE_LAST = -1..-1 + TEXT_END = "';" def self.h(value) value.to_s.gsub(/[&<>"']/){|s| ESCAPE_TABLE[s]} end # :nocov: end class Engine - # The ruby source code generated from the template, which can be evaled. + # The frozen ruby source code generated from the template, which can be evaled. attr_reader :src # The filename of the template, if one was given. attr_reader :filename @@ -61,16 +63,16 @@ @src = src = properties[:src] || String.new src << "# frozen_string_literal: true\n" if properties[:freeze] src << "begin; __original_outvar = #{bufvar} if defined?(#{bufvar}); " if properties[:ensure] - unless escapefunc = properties[:escapefunc] + unless @escapefunc = properties[:escapefunc] if escape - escapefunc = '__erubi.h' + @escapefunc = '__erubi.h' src << "__erubi = ::Erubi;" else - escapefunc = '::Erubi.h' + @escapefunc = '::Erubi.h' end end src << preamble @@ -113,13 +115,13 @@ case ch when '=' rspace = nil if tailch && !tailch.empty? add_text(lspace) if lspace if ((indicator == '=') ^ escape) - src << " #{bufvar} << (" << code << ').to_s;' + add_expression_result(code) else - src << " #{bufvar} << #{escapefunc}((" << code << '));' + add_expression_result_escaped(code) end add_text(rspace) if rspace when '#' n = code.count("\n") + (rspace ? 1 : 0) if trim @@ -147,23 +149,34 @@ add_text(rest) src << "\n" unless src[RANGE_LAST] == "\n" src << postamble src << "; ensure\n #{bufvar} = __original_outvar\nend\n" if properties[:ensure] + src.freeze freeze end private # Add raw text to the template def add_text(text) - @src << " #{@bufvar} << '" << text.gsub(/['\\]/, '\\\\\&') << "';" unless text.empty? + @src << " #{@bufvar} << '" << text.gsub(/['\\]/, '\\\\\&') << TEXT_END unless text.empty? end # Add ruby code to the template def add_code(code) @src << code @src << ';' unless code[RANGE_LAST] == "\n" + end + + # Add the result of Ruby expression to the template + def add_expression_result(code) + @src << " #{@bufvar} << (" << code << ').to_s;' + end + + # Add the escaped result of Ruby expression to the template + def add_expression_result_escaped(code) + @src << " #{@bufvar} << #{@escapefunc}((" << code << '));' end # Raise an exception, as the base engine class does not support handling other indicators. def handle(indicator, code, tailch, rspace, lspace) raise ArgumentError, "Invalid indicator: #{indicator}"