Module: Ferrum::Page::Stream

Included in:
Ferrum::Page
Defined in:
lib/ferrum/page/stream.rb

Constant Summary collapse

STREAM_CHUNK =
128 * 1024

Instance Method Summary collapse

Instance Method Details

#stream(output:, handle:) ⇒ Object



27
28
29
30
31
32
33
34
35
# File 'lib/ferrum/page/stream.rb', line 27

def stream(output:, handle:)
  loop do
    result = command("IO.read", handle: handle, size: STREAM_CHUNK)
    chunk = result.fetch("data")
    chunk = Base64.decode64(chunk) if result["base64Encoded"]
    output << chunk
    break if result["eof"]
  end
end

#stream_to(path:, encoding:, handle:) ⇒ Object



8
9
10
11
12
13
14
# File 'lib/ferrum/page/stream.rb', line 8

def stream_to(path:, encoding:, handle:)
  if path.nil?
    stream_to_memory(encoding: encoding, handle: handle)
  else
    stream_to_file(path: path, handle: handle)
  end
end

#stream_to_file(path:, handle:) ⇒ Object



16
17
18
19
# File 'lib/ferrum/page/stream.rb', line 16

def stream_to_file(path:, handle:)
  File.open(path, "wb") { |f| stream(output: f, handle: handle) }
  true
end

#stream_to_memory(encoding:, handle:) ⇒ Object



21
22
23
24
25
# File 'lib/ferrum/page/stream.rb', line 21

def stream_to_memory(encoding:, handle:)
  data = String.new # Mutable string has << and compatible to File
  stream(output: data, handle: handle)
  encoding == :base64 ? Base64.encode64(data) : data
end