Open an IO stream from a local file or url

RubyStream

Ruby Problem Overview


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?

Ruby Solutions


Solution 1 - 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 }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncsextonView Question on Stackoverflow
Solution 1 - RubyAaron HinniView Answer on Stackoverflow