Sha256: 6cb01bbdb623246b81eb19f1eda6bda761d00a2ed350c1aa3849050948a5c37f

Contents?: true

Size: 1.11 KB

Versions: 1

Compression:

Stored size: 1.11 KB

Contents

# encoding: utf-8

module Hatetepe
  class Body
    include Promise::Attribute
    promise :closed

    def self.build(arg)
      if arg.is_a?(Body)
        arg
      else
        body = new(arg.to_str)
        body.closed.fulfill
        body
      end
    end

    def initialize(string = '')
      @io = StringIO.new(string)

      closed.on_progress { |str| @io.write(str) }
    end

    # don't optimize the sync call, we don't wanna search in @io.string
    # because search time increases with its size.
    def gets(*args)
      closed.sync
      @io.gets(*args)
    end

    def read(length = nil, buffer = nil)
      closed.sync unless optimized_read?(length)
      @io.read(length, buffer)
    end

    def rewind
      closed.sync
      @io.rewind
    end

    def each(&block)
      yield_string(&block)
      closed.on_progress(&block)
      closed.sync
    end

    def to_s
      closed.sync
      @io.string
    end

    private

    def optimized_read?(length)
      length && length < (@io.length - pos)
    end

    def yield_string(&block)
      block.call(@io.string) unless @io.string.empty?
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
hatetepe-0.6.0.pre.1 lib/hatetepe/body.rb