Sha256: f127dca53c8b2494daa301a604920baafb6d096a3d03ac78a2945724d5416dab

Contents?: true

Size: 1.09 KB

Versions: 175

Compression:

Stored size: 1.09 KB

Contents

# frozen_string_literal: true

require "ripper"

module Primer
  module Forms
    # :nodoc:
    class BufferRewriter < Ripper
      class << self
        def rewrite(code)
          parser = new(code, "(code)", 0)
          parser.parse

          line_offsets = calc_line_offsets(code)

          code.dup.tap do |result|
            parser.var_refs.reverse_each do |lineno, stop|
              line_offset = line_offsets[lineno]
              stop += line_offset
              stop -= 1 if stop < code.length
              start = stop - "@output_buffer".length
              result[start...stop] = "output_buffer"
            end
          end
        end

        private

        def calc_line_offsets(code)
          idx = -1

          [0].tap do |offsets|
            while (idx = code.index(/\r?\n/, idx + 1))
              offsets << Regexp.last_match.end(0)
            end
          end
        end
      end

      def on_var_ref(var)
        return unless var == "@output_buffer"

        var_refs << [lineno, column]
      end

      def var_refs
        @var_refs ||= []
      end
    end
  end
end

Version data entries

175 entries across 175 versions & 2 rubygems

Version Path
primer_view_components-0.36.5 app/lib/primer/forms/buffer_rewriter.rb
openproject-primer_view_components-0.52.2 app/lib/primer/forms/buffer_rewriter.rb
primer_view_components-0.36.4 app/lib/primer/forms/buffer_rewriter.rb
openproject-primer_view_components-0.52.1 app/lib/primer/forms/buffer_rewriter.rb
openproject-primer_view_components-0.52.0 app/lib/primer/forms/buffer_rewriter.rb
primer_view_components-0.36.3 app/lib/primer/forms/buffer_rewriter.rb
openproject-primer_view_components-0.51.0 app/lib/primer/forms/buffer_rewriter.rb
primer_view_components-0.36.2 app/lib/primer/forms/buffer_rewriter.rb
openproject-primer_view_components-0.50.1 app/lib/primer/forms/buffer_rewriter.rb
openproject-primer_view_components-0.50.0 app/lib/primer/forms/buffer_rewriter.rb
primer_view_components-0.36.1 app/lib/primer/forms/buffer_rewriter.rb
primer_view_components-0.36.0 app/lib/primer/forms/buffer_rewriter.rb
openproject-primer_view_components-0.49.2 app/lib/primer/forms/buffer_rewriter.rb
primer_view_components-0.35.2 app/lib/primer/forms/buffer_rewriter.rb
openproject-primer_view_components-0.49.1 app/lib/primer/forms/buffer_rewriter.rb
openproject-primer_view_components-0.49.0 app/lib/primer/forms/buffer_rewriter.rb
primer_view_components-0.35.1 app/lib/primer/forms/buffer_rewriter.rb
primer_view_components-0.35.0 app/lib/primer/forms/buffer_rewriter.rb
openproject-primer_view_components-0.48.2 lib/primer/forms/buffer_rewriter.rb
openproject-primer_view_components-0.48.1 lib/primer/forms/buffer_rewriter.rb