0

My below code snippet is not working as expected. I wanted to download the mp4 or image file from given link/URL. However my code is not working as expected. I found the similar solution over internet but it is not working. I am using ruby 3.0 version in my environment.

url = "https://images.pexels.com/photos/60597/dahlia-red-blossom-bloom-60597.jpeg?cs=srgb&dl=pexels-pixabay-60597.jpg&fm=jpg"
new_file_path = "/Users/{username}/Documents/test.jpg"
open(new_file_path, "wb") do |file| 
  file.print open(url).read
end

I am getting below error here.

test.rb:4:in `initialize': No such file or directory @ rb_sysopen - https://images.pexels.com/photos/60597/dahlia-red-blossom-bloom-60597.jpeg?cs=srgb&dl=pexels-pixabay-60597.jpg&fm=jpg (Errno::ENOENT)
    from test.rb:4:in `open'
    from test.rb:4:in `block in <main>'
    from test.rb:3:in `open'
    from test.rb:3:in `<main>'

Any suggestion here to make it work.

sagar verma
  • 404
  • 4
  • 10
  • 1
    You are looking for [`URI::open`](https://ruby-doc.org/stdlib-3.0.1/libdoc/open-uri/rdoc/OpenURI.html) not `Kernel#open` (which is what you are using right now). `URI` used to bastardize the implementation of `Kernel#open` such that it would work with URIs as well but this was deprecated in 2.7 removed completely in 3.0 I believe, in favor of calling `URI.open` directly – engineersmnky Jul 06 '22 at 17:54
  • @engineersmnky Could you please suggest exact code snippet if possible here. Since I am a beginner to Ruby. – sagar verma Jul 06 '22 at 17:57
  • 1
    Add `require 'open-uri'` to the top of the file and then change `file.print open(url).read` to `file.print URI.open(url).read` – engineersmnky Jul 06 '22 at 17:59
  • Thanks it worked. One more question here. Can I use the same code to download the video file and store the video file in memory via some object and then use the same object to upload to google cloud ? – sagar verma Jul 06 '22 at 18:02
  • While I have never tried it this answer https://stackoverflow.com/a/5684654/1978251 seems to suggest that you can – engineersmnky Jul 06 '22 at 18:26

0 Answers0