Sha256: 9864a9a153ae126af3c5e7827ab58b83a76498a0142cd59b61e6d28b0c4a8c45

Contents?: true

Size: 1.18 KB

Versions: 1

Compression:

Stored size: 1.18 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

    # TODO: eliminate string param
    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

    def string
      @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.2 lib/hatetepe/body.rb