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
openproject-primer_view_components-0.6.3 lib/primer/forms/buffer_rewriter.rb
primer_view_components-0.6.0 lib/primer/forms/buffer_rewriter.rb
primer_view_components-0.5.1 lib/primer/forms/buffer_rewriter.rb
primer_view_components-0.5.0 lib/primer/forms/buffer_rewriter.rb
primer_view_components-0.4.0 lib/primer/forms/buffer_rewriter.rb
primer_view_components-0.3.1 lib/primer/forms/buffer_rewriter.rb
primer_view_components-0.3.0 lib/primer/forms/buffer_rewriter.rb
primer_view_components-0.2.0 lib/primer/forms/buffer_rewriter.rb
primer_view_components-0.1.9 lib/primer/forms/buffer_rewriter.rb
primer_view_components-0.1.8 lib/primer/forms/buffer_rewriter.rb
primer_view_components-0.1.7 lib/primer/forms/buffer_rewriter.rb
primer_view_components-0.1.6 lib/primer/forms/buffer_rewriter.rb
primer_view_components-0.1.5 lib/primer/forms/buffer_rewriter.rb
primer_view_components-0.1.4 lib/primer/forms/buffer_rewriter.rb
primer_view_components-0.1.3 lib/primer/forms/buffer_rewriter.rb
primer_view_components-0.1.2 lib/primer/forms/buffer_rewriter.rb
primer_view_components-0.1.1 lib/primer/forms/buffer_rewriter.rb
primer_view_components-0.1.0 lib/primer/forms/buffer_rewriter.rb
primer_view_components-0.0.123 lib/primer/forms/buffer_rewriter.rb
primer_view_components-0.0.122 lib/primer/forms/buffer_rewriter.rb