简体   繁体   中英

Open an IO stream from a local file or url

I know there are libs in other languages that can take a string that contains either a path to a local file or a url and open it as a readable IO stream.

Is there an easy way to do this in ruby?

open-uri is part of the standard Ruby library, and it will redefine the behavior of open so that you can open a url, as well as a local file. It returns a File object, so you should be able to call methods like read and readlines .

require 'open-uri'
file_contents = open('local-file.txt') { |f| f.read }
web_contents  = open('http://www.stackoverflow.com') {|f| f.read }

For url, you may want rest-client , from its document

If you want to stream the data from the response to a file as it comes, rather than entirely in memory, you can also pass RestClient::Request.execute a parameter :block_response to which you pass a block/proc.This block receives the raw unmodified Net::HTTPResponse object from Net::HTTP, which you can use to stream directly to a file as each chunk is received.

File.open('/some/output/file', 'w') {|f|
  block = proc { |response|
    response.read_body do |chunk|
      f.write chunk
    end
  }
  RestClient::Request.execute(method: :get,
                              url: 'http://example.com/some/really/big/file.img',
                              block_response: block)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM