Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read content of remote file in Ruby on Rails?

here my file: http://example.com/test.txt

i have to read content of http://example.com/test.txt (a JSON string) and parse it in Ruby

like image 999
Leonardo Avatar asked Nov 16 '11 09:11

Leonardo


People also ask

What are the ruby file open modes?

Ruby allows the following open modes: "r" Read-only, starts at beginning of file (default mode). "r+" Read-write, starts at beginning of file. "w" Write-only, truncates existing file to zero length or creates a new file for writing.

How do you download a file in Ruby?

Plain old Ruby The most popular way to download a file without any dependencies is to use the standard library open-uri . open-uri extends Kernel#open so that it can open URIs as if they were files. We can use this to download an image and then save it as a file.


2 Answers

I would suggest using open-uri:

require 'json'
require 'open-uri'
result = JSON.parse open('http://example.com/data.json').read
like image 116
KL-7 Avatar answered Oct 13 '22 01:10

KL-7


require 'net/http'
uri = URI('http://my.json.emitter/some/action')
json = Net::HTTP.get(uri)

json will contain the JSON string you fetched from uri.

Then read this StackOverflow post.

like image 32
dave Avatar answered Oct 13 '22 01:10

dave