Open an I / O stream from a local file or URL

I know that in other languages ​​there are libs that can take a string containing either the path to a local file or a URL and open it as a readable input / output stream.

Is there an easy way to do this in ruby?

+84
ruby stream
Nov 04 '08 at 21:36
source share
2 answers

open-uri is part of the Ruby standard library and it will override the open behavior so that you can open the URL as well as the 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 } 
+187
Nov 05 '08 at 3:00
source share

For the url you may need the rest-client from its doc

If you want to transfer the data from the response to the file as it arrives, and not completely into memory, you can also pass the RestClient :: Request.execute parameter: block_response to which you pass the /proc.This block, the block receives the original unmodified Net :: object. HTTPResponse from Net :: HTTP, which you can use to stream directly to a file when receiving each fragment.

 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) } 
0
Jun 01 '17 at 16:59 on
source share



All Articles