115

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?

1 Answer 1

245

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 }
7
  • 2
    Is there a way to return a file object like you did here from an ActionMailer attachment? Commented Dec 6, 2010 at 0:03
  • 9
    Know this is a bit old now, but you can also do: content = open("http://example.com").read
    – Automatico
    Commented Feb 15, 2014 at 18:30
  • 7
    You can, but doing it outside the closure like that will keep the file descriptor open. This may be a problem for some usages. Commented Feb 17, 2014 at 3:57
  • 27
    note that 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.
    – zed_0xff
    Commented May 15, 2014 at 19:57
  • 16
    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. Commented Oct 3, 2018 at 19:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.