0

Let's say I have the following file in my working directory:

path/to/my/file/fileToBeReplaced.json

And I have a file at the following URL endpoint:

mywebsite.com/fileToCopy.json

I want to take the file at the URL endpoint (fileToCopy.json) and fetch the contents there to overwrite the file in my working directory (fileToBeReplaced.json). It's also important that I preserve the json formatting when writing the file to my working directory. How can this be accomplished within a Ruby script?

cvoep28
  • 423
  • 5
  • 9
  • 21
  • Possible duplicate http://stackoverflow.com/questions/2515931/how-can-i-download-a-file-from-a-url-and-save-it-in-rails – Alex Zhevzhik Aug 31 '15 at 18:50

1 Answers1

2

You can do something like this:

require 'net/http'

File.open("path/to/my/file/fileToBeReplaced.json", "w") do |f|
   f.write Net::HTTP.get('mywebsite.com', '/fileToCopy.json')
end

If your JSON from URL is not well formatted, then, you can try something like this:

require 'net/http'
require 'json'

File.open("path/to/my/file/fileToBeReplaced.json", "w") do |f|
   json_str = Net::HTTP.get('mywebsite.com', '/fileToCopy.json')
   json_hash = JSON.parse(json_str)
   f.puts JSON.pretty_generate(json_hash)
end
Wand Maker
  • 18,476
  • 8
  • 53
  • 87
  • This works but doesn't preserve the json formatting. I've tried adding "to_json" to the end of the f.write line, but it just inserts /'s in place of white space. – cvoep28 Aug 31 '15 at 19:10
  • Hmm... I got the file with formatting preserved. Does your URL return JSON with formatting ? Updated my answer to show usage of `JSON#pretty_generate` – Wand Maker Aug 31 '15 at 19:11
  • 1
    It looks like I was using Ruby 1.8 for this. The hash function is undefined in 1.8, but is insertion order for 1.9, so upgrading fixed this issue. – cvoep28 Sep 03 '15 at 20:12