Sha256: 017e254f19674901ce660132efe1e5e73876cae9cfc5751a13838c6ab5fb2887

Contents?: true

Size: 1.65 KB

Versions: 2

Compression:

Stored size: 1.65 KB

Contents

# encoding: UTF-8

class YamlWriteStream
  class YieldingWriter
    attr_reader :emitter, :stream, :first

    def initialize(emitter, stream)
      @emitter = emitter
      @stream = stream
      @first = true
    end

    def flush
      # psych gets confused if you open a file and don't at least
      # pretend to write something
      write_scalar('') if first
      emitter.end_document(true)
      emitter.end_stream
      nil
    end

    def close
      flush
      stream.close
      nil
    end

    def write_sequence
      @first = false

      # anchor, tag, implicit, style
      emitter.start_sequence(
        nil, nil, true, Psych::Nodes::Sequence::ANY
      )

      yield YieldingSequenceWriter.new(emitter, stream)
      emitter.end_sequence
    end

    def write_map
      @first = false

      # anchor, tag, implicit, style
      emitter.start_mapping(
        nil, nil, true, Psych::Nodes::Sequence::ANY
      )

      yield YieldingMappingWriter.new(emitter, stream)
      emitter.end_mapping
    end

    protected

    def write_scalar(value)
      @first = false

        # value, anchor, tag, plain, quoted, style
      emitter.scalar(
        value, nil, nil, true, false, Psych::Nodes::Scalar::ANY
      )
    end
  end

  class YieldingMappingWriter < YieldingWriter
    def write_map(key)
      write_scalar(key)
      super()
    end

    def write_sequence(key)
      write_scalar(key)
      super()
    end

    def write_key_value(key, value)
      @first = false
      write_scalar(key)
      write_scalar(value)
    end
  end

  class YieldingSequenceWriter < YieldingWriter
    def write_element(element)
      write_scalar(element)
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
yaml-write-stream-1.0.2 lib/yaml-write-stream/yielding.rb
yaml-write-stream-1.0.1 lib/yaml-write-stream/yielding.rb