Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: abort OpenURI based on content length

Tags:

ruby

open-uri

Ruby's OpenURI provides a content_length_proc option which allows determining* content length before the actual transfer is started:

open(url, :content_length_proc => lambda { |content_length|
  puts "Content Length: #{content_length}"
}) { |data|
   # data.meta, data.read etc.
}

Is there a way for this proc to abort the actual, full retrieval?

* I'm aware this is not reliable - but it's sufficient for a simple heuristic in my case

like image 862
AnC Avatar asked Mar 17 '26 21:03

AnC


1 Answers

This is the corresponding code from open-uri.rb:

if options[:content_length_proc] && Net::HTTPSuccess === resp
  if resp.key?('Content-Length')
    options[:content_length_proc].call(resp['Content-Length'].to_i)
  else
    options[:content_length_proc].call(nil)
  end
end
resp.read_body {|str|
  ...
}

So as you can see the return value of content_length_proc is ignored. But, what you could simply do to cancel the operation is raise some form of error in the callback - this will effectively abort further execution. If you raise a dedicated error class you could even rescue it and react to that specific situation:

begin
  open(url, :content_length_proc => lambda { |content_length|
    puts "Content Length: #{content_length}"
  }) { |data|
    # data.meta, data.read etc.
  }
rescue MyError
  # react to it
end
like image 100
emboss Avatar answered Mar 19 '26 22:03

emboss



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!