erubi.rb 2.4 KB
Newer Older
1 2
# frozen_string_literal: true

3 4 5 6 7 8 9 10 11 12 13 14 15
require "erubi"

module ActionView
  class Template
    module Handlers
      class ERB
        class Erubi < ::Erubi::Engine
          # :nodoc: all
          def initialize(input, properties = {})
            @newline_pending = 0

            # Dup properties so that we don't modify argument
            properties = Hash[properties]
16

17 18
            properties[:preamble]   ||= ""
            properties[:postamble]  ||= "@output_buffer.to_s"
19

20 21 22 23 24 25 26
            properties[:bufvar]     = "@output_buffer"
            properties[:escapefunc] = ""

            super
          end

          def evaluate(action_view_erb_handler_context)
27 28 29
            src = @src
            view = Class.new(ActionView::Base) {
              include action_view_erb_handler_context._routes.url_helpers
30
              class_eval("define_method(:_template) { |local_assigns, output_buffer| #{src} }", defined?(@filename) ? @filename : "(erubi)", 0)
31
            }.empty
32
            view._run(:_template, nil, {}, ActionView::OutputBuffer.new)
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
          end

        private
          def add_text(text)
            return if text.empty?

            if text == "\n"
              @newline_pending += 1
            else
              src << "@output_buffer.safe_append='"
              src << "\n" * @newline_pending if @newline_pending > 0
              src << text.gsub(/['\\]/, '\\\\\&')
              src << "'.freeze;"

              @newline_pending = 0
            end
          end

          BLOCK_EXPR = /\s*((\s+|\))do|\{)(\s*\|[^|]*\|)?\s*\Z/

          def add_expression(indicator, code)
            flush_newline_if_pending(src)

            if (indicator == "==") || @escape
              src << "@output_buffer.safe_expr_append="
            else
              src << "@output_buffer.append="
            end

            if BLOCK_EXPR.match?(code)
              src << " " << code
            else
              src << "(" << code << ");"
            end
          end

          def add_code(code)
            flush_newline_if_pending(src)
            super
          end

          def add_postamble(_)
            flush_newline_if_pending(src)
            super
          end

          def flush_newline_if_pending(src)
            if @newline_pending > 0
              src << "@output_buffer.safe_append='#{"\n" * @newline_pending}'.freeze;"
              @newline_pending = 0
            end
          end
        end
      end
    end
  end
end