lib/trenni/template.rb in trenni-2.1.0 vs lib/trenni/template.rb in trenni-3.0.0

- old
+ new

@@ -57,13 +57,12 @@ def self.buffer(binding) binding.local_variable_get(OUT) end class Assembler - def initialize(filter: String, encoding: Encoding::UTF_8) + def initialize(encoding: Encoding::UTF_8) @code = String.new.force_encoding(encoding) - @filter = filter end attr :code # Output raw text to the template. @@ -81,35 +80,42 @@ end # Output a string interpolation. def expression(text) # Double brackets are required here to handle expressions like #{foo rescue "bar"}. - @code << "#{OUT}<<#{@filter}((#{text}));" + @code << "#{OUT}<<String(#{text});" end end - def self.load_file(path, **options) - self.new(FileBuffer.new(path), **options) + def self.load_file(path, *args) + self.new(FileBuffer.new(path), *args).freeze end - def initialize(buffer, filter: String) + def initialize(buffer) @buffer = buffer - @filter = filter end - - def to_string(scope = Object.new, output = output_buffer) + + def freeze + return self if frozen? + + to_proc + + super + end + + def to_string(scope = Object.new, output = nil) output ||= output_buffer scope.instance_exec(output, &to_proc) end def to_buffer(scope) Buffer.new(to_string(scope), path: @buffer.path) end - + def to_proc(scope = nil) - @compiled_proc ||= eval("proc{|#{OUT}|;#{code};#{OUT}}", scope, @buffer.path) + @compiled_proc ||= eval("proc{|#{OUT}|;#{code};#{OUT}}", scope, @buffer.path).freeze end protected def output_buffer @@ -118,24 +124,38 @@ def code @code ||= compile! end + def make_assembler + Assembler.new + end + def compile! - assembler = Assembler.new(filter: @filter) + assembler = make_assembler Parsers.parse_template(@buffer, assembler) assembler.code end end class MarkupTemplate < Template - def initialize(buffer, filter: MarkupString) - super + class Assembler < Template::Assembler + # Output a string interpolation. + def expression(text) + @code << "Markup.append(#{OUT},(#{text}));" + end end - # The output of the markup template is encoded markup (e.g. with entities, tags, etc) + protected + + # We need an assembler which builds specific `Markup.append` sequences. + def make_assembler + Assembler.new + end + + # The output of the markup template is encoded markup (e.g. with entities, tags, etc). def output_buffer MarkupString.new.force_encoding(code.encoding) end end end