attr_accessor 在 procs 中使用时无效

attr_accessor won't work when used in procs

我写了以下代码片段来下载我需要的一些文件。

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

问题是总大小不会打印在最后一行,即使它已经在 content_length_proc 中设置。

为什么会这样?

even though it has already been set in content_length_proc

否,尚未设置。您在那里设置了一个局部变量 size,而不是访问器。新手错误。更改为:

self.size = bytes_to_megabytes(t).round