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
This is the corresponding code from open-uri.rb:
So as you can see the return value of
content_length_procis 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: