Sha256: 50a86e5a66f1bc1946af74b9b6a8a8c46c5f0a7058b0174b29470c33a1eaa212

Contents?: true

Size: 1.81 KB

Versions: 10

Compression:

Stored size: 1.81 KB

Contents

# frozen_string_literal: true

module Unparser

  # Buffer used to emit into
  class Buffer

    NL = "\n".freeze

    # Initialize object
    #
    # @return [undefined]
    #
    # @api private
    #
    def initialize
      @content = +''
      @indent = 0
    end

    # Append string
    #
    # @param [String] string
    #
    # @return [self]
    #
    # @api private
    #
    def append(string)
      if @content[-1].eql?(NL)
        prefix
      end
      write(string)
      self
    end

    # Append a string without an indentation prefix
    #
    # @param [String] string
    #
    # @return [self]
    #
    # @api private
    #
    def append_without_prefix(string)
      write(string)
    end

    # Increase indent
    #
    # @return [self]
    #
    # @api private
    #
    def indent
      @indent += 1
      self
    end

    # Decrease indent
    #
    # @return [self]
    #
    # @api private
    #
    def unindent
      @indent -= 1
      self
    end

    # Write newline
    #
    # @return [self]
    #
    # @api private
    #
    def nl
      write(NL)
    end

    def root_indent
      before = @indent
      @indent = 0
      yield
      @indent = before
    end

    # Test for a fresh line
    #
    # @return [Boolean]
    #
    # @api private
    #
    def fresh_line?
      @content.empty? || @content[-1].eql?(NL)
    end

    # Return content of buffer
    #
    # @return [String]
    #
    # @api private
    #
    def content
      @content.dup.freeze
    end

    # Write raw fragment to buffer
    #
    # Does not do indentation logic.
    #
    # @param [String] fragment
    #
    # @return [self]
    def write(fragment)
      @content << fragment
      self
    end

  private

    INDENT_SPACE = '  '.freeze

    def prefix
      write(INDENT_SPACE * @indent)
    end

  end # Buffer
end # Unparser

Version data entries

10 entries across 10 versions & 2 rubygems

Version Path
unparser-0.6.15 lib/unparser/buffer.rb
unparser-0.6.14 lib/unparser/buffer.rb
unparser-0.6.13 lib/unparser/buffer.rb
unparser-0.6.12 lib/unparser/buffer.rb
unparser-0.6.10 lib/unparser/buffer.rb
unparser-0.6.9 lib/unparser/buffer.rb
unparser-0.6.8 lib/unparser/buffer.rb
devcycle-ruby-server-sdk-2.0.0 vendor/bundle/ruby/3.0.0/gems/unparser-0.6.7/lib/unparser/buffer.rb
unparser-0.6.7 lib/unparser/buffer.rb
unparser-0.6.6 lib/unparser/buffer.rb