I wrote the following snippet to download some files I need to.
require 'open-uri'
MEGABYTE = 1024.0 * 1024.0
def bytes_to_megabytes(bytes)
bytes / MEGABYTE
end
class Downloader
class << self
attr_accessor :size
def get(resource)
open(resource,
content_length_proc: proc do |t|
size = bytes_to_megabytes(t).round
puts "Total size is: #{size}"
end,
progress_proc: proc do |step|
# size won't print here!
puts "Downloading #{bytes_to_megabytes(step).round} out of #{size}"
end )
end
end
end
Problem is the total size won't print on the last line even though it has already been set in content_length_proc
.
Why is this happening?
even though it has already been set in
content_length_proc
No, it hasn't been set. You set a local variable size
there, not the accessor. Rookie mistake. Change to this:
self.size = bytes_to_megabytes(t).round