Leonardo
Leonardo

Reputation: 2363

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

Upvotes: 17

Views: 21635

Answers (3)

Dmitrii Kharlamov
Dmitrii Kharlamov

Reputation: 309

require 'json'
require 'open-uri'

uri = URI.parse 'http://example.com/test.txt'
json =
  begin
    json_file = uri.open.read
  rescue OpenURI::HTTPError => e
    puts "Encountered error pulling the file: #{e}"
  else
    JSON.parse json_file
  end
  1. I specifically include open-uri, so that open is called from that module instead of attempting to call a private open from the Kernel module.
  2. I intentionally parse the URL to avoid a security risk - https://rubydoc.info/gems/rubocop/RuboCop/Cop/Security/Open
  3. Unlike some commenters pointed out above, OpenURI does indicate the HTTP status code of an error.

Upvotes: 1

KL-7
KL-7

Reputation: 47618

I would suggest using open-uri:

require 'json'
require 'open-uri'
result = JSON.parse open('http://example.com/data.json').read

Upvotes: 25

dave
dave

Reputation: 2269

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.

Upvotes: 6

Related Questions