Class: RestMan::Request::FetchBodyToTempfile

Inherits:
ActiveMethod::Base
  • Object
show all
Defined in:
lib/restman/request/fetch_body_to_tempfile.rb

Instance Method Summary collapse

Instance Method Details

#callObject



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/restman/request/fetch_body_to_tempfile.rb', line 7

def call
  # Taken from Chef, which as in turn...
  # Stolen from http://www.ruby-forum.com/topic/166423
  # Kudos to _why!
  tf = Tempfile.new('rest-man.')
  tf.binmode

  size = 0
  total = http_response['Content-Length'].to_i
  stream_log_bucket = nil

  http_response.read_body do |chunk|
    tf.write chunk
    size += chunk.size
    if log
      if total == 0
        log << "streaming %s %s (%d of unknown) [0 Content-Length]\n" % [method.upcase, url, size]
      else
        percent = (size * 100) / total
        current_log_bucket, _ = percent.divmod(stream_log_percent)
        if current_log_bucket != stream_log_bucket
          stream_log_bucket = current_log_bucket
          log << "streaming %s %s %d%% done (%d of %d)\n" % [method.upcase, url, (size * 100) / total, size, total]
        end
      end
    end
  end
  tf.close
  tf
end