What if I want to use Ruby to download a file on the Internet and save it locally?
First is an example of a text file. If you want to download Wikipedia --HyperText Markup Language as an HTML file, write as follows.
require 'open-uri'
uri_str = 'https://ja.wikipedia.org/wiki/HyperText_Markup_Language'
URI.open(uri_str) do |res|
IO.copy_stream(res, 'HyperText_Markup_Language.html')
end
The same is true for binaries like images. Download the image given as an example PNG file in Wikipedia --Portable Network Graphics.
require 'open-uri'
uri_str = 'https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png'
URI.open(uri_str) do |res|
IO.copy_stream(res, 'PNG_transparency_demonstration_1.png')
end
The ʻopen-uri library is a wrapper such as
Net :: HTTP Net :: HTTPS
Net :: FTPthat allows you to treat http and https URLs like regular files. This library redefines
Kernel # open`, so you can also write:
require 'open-uri'
uri_str = 'https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png'
open(uri_str) do |res|
IO.copy_stream(res, 'PNG_transparency_demonstration_1.png')
end
However, starting with Ruby 2.7, opening URIs using Kernel # open
, which is extended by ʻopen-uri`, has been deprecated. When I run the above code on Ruby 2.7, I get the following warning:
warning: calling URI.open via Kernel#open is deprecated, call URI.open directly or use URI#open
It doesn't mean that it doesn't stop just because of the warning, but it is recommended to use ʻURI # open or ʻOpenURI # open_uri
.
$ ruby -v
ruby 2.7.1p83 (2020-03-31 revision a0c7c23c9c) [x86_64-darwin18
Recommended Posts