module Juglight
  class DeferrableBody
    include EventMachine::Deferrable

    def initialize
      @queue = []
    end

    def schedule_dequeue
      return unless @body_callback
      EventMachine::next_tick do
        next unless body = @queue.shift
        @body_callback.call(body)
        schedule_dequeue unless @queue.empty?
      end
    end

    def <<(body)
      @queue << body
      schedule_dequeue
    end

    def each &blk
      @body_callback = blk
      schedule_dequeue
    end

  end
end

module Juglight
  class DeferrableBody
    include EventMachine::Deferrable

    def initialize
      @queue = EM::Queue.new
    end

    def write(body)
      @queue.push(body)
    end

    def each &blk
      @body_callback = blk
      processor = proc { |item|
        @body_callback.call(item)
        @queue.pop(&processor)
      }
      @queue.pop(&processor)
    end
  end
end

Use EM::Queue for DeferrableBody so writing doesn't block
Use EM::Queue for DeferrableBody so writing doesn't block