Sha256: fbef730d96f5508af65a009a739fd888a4e1a958e7876ba741835f2153ddaff8

Contents?: true

Size: 1.6 KB

Versions: 1

Compression:

Stored size: 1.6 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 close
      # 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
      stream.close
    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

1 entries across 1 versions & 1 rubygems

Version Path
yaml-write-stream-1.0.0 lib/yaml-write-stream/yielding.rb