0

I have a method that waits for a chrome download to start, using Watir. However, I'd like to simplify and respecify this to the point where it simply checks if the directory size increases. I'm assuming this is going to require me to save the directory's size at the beginning of the block, and then wait for the Dir size to be equal to that number + 1.

 def wait_for_download
     dl_dir = Dir["#{Dir.pwd}/downloads/*"].to_s
     Watir::Wait.until { !dl_dir.include?(".crdownload") }
 end
  • That would open yourself up to a race condition where the size of the download increases before the `Watir::Wait.until` block is called. To verify size, you would need to store the directory size first, then take the action, then wait for the size to increase by one. – titusfortner Jun 08 '16 at 21:29
  • I hate this solution so much that I downvoted the guy's answer before I took it back, but there is apparently a gem for this: http://stackoverflow.com/questions/9354595/recursively-getting-the-size-of-a-directory – boulder_ruby Jun 09 '16 at 00:59
  • If you are downloading a file, why do you need to check that the size _increased_? I would expect you would be going from not having a file to having at least part of the file - ie couldn't you simply check that the file size is greater than 0? – Justin Ko Jun 10 '16 at 18:24
  • That's correct Justin, that's what I'm trying to do – Vincent Rodomista Jun 10 '16 at 18:35

1 Answers1

0

This is just a couple of functions you can add in your initializers or whatever.

def get_file_size_in_mb(path)
  File.size(path).to_f / 10240000.0
end

def find_all_files_inside(folder_path)
  Dir.glob("#{folder_path}/**/*")
end 

def calculate_size_of_folder_contents(folder_path)
  mb = 0.0
  find_all_files_inside(folder_path).each do |fn|
    mb += get_file_size_in_mb(fn)
  end# ^ could have used `inject` here
  mb
end

def wait_until_folder_size_changes(folder_path, seconds=2)
  while true
    size0 = calculate_size_of_folder_contents(folder_path)
    sleep seconds
    size1 = calculate_size_of_folder_contents(folder_path)
    break if (size1-size0) > 0
  end
end

Haven't tested, but seems functionally sound

You could also easily monkey code this into watir itself

boulder_ruby
  • 38,457
  • 9
  • 79
  • 100