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?
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 }
content = open("http://example.com").read
–
Ribeiro open-uri
will not stream a file, so you can't read a first 4k of it. open-uri
will read a whole file to memory at moment of opening. –
Teerell URI.parse('http://www.stackoverflow.com').open { |f| f.read }
If you looking for a way to insure it does not call Kernal.open
. Also gets around rubocop security rules. –
Cyrillus open-uri
isn't needed with Ruby 2.7.1. I don't know for the other versions. –
Atween open
call now throws: "(irb):2:in `initialize': No such file or directory @ rb_sysopen - stackoverflow.com (Errno::ENOENT)" –
Wholesale © 2022 - 2024 — McMap. All rights reserved.