Does Ruby's 'open_uri' reliably close sockets after read or on fail?

限于喜欢 提交于 2019-12-05 11:01:48

I suspect you are not closing the handles. OpenURI's docs start with this comment:

It is possible to open http/https/ftp URL as usual like opening a file:

open("http://www.ruby-lang.org/") {|f|
  f.each_line {|line| p line}
}

I looked at the source and the open_uri method does close the stream if you pass a block, so, tweaking the above example to fit your code:

uri = ''
open("http://www.ruby-lang.org/") {|f|
  uri = f.read
}

Should get you close to what you want.


Here's one way to handle exceptions:

# The list of URLs to pass in to check if one times out or is refused.
urls = %w[
  http://www.ruby-lang.org/
  http://www2.ruby-lang.org/
]

# the method
def self.read_uri(urls)

  content = ''

  open(urls.shift) { |f| content = f.read }
  content == "Error" ? nil : content

  rescue OpenURI::HTTPError
    retry if (urls.any?)
    nil
end

Try using a block:

data = open(uri){|f| f.read}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!