Ruby's OpenURI is dangerous and should not be used in production. This is an alternative.
Last active
August 1, 2019 13:48
-
-
Save stevehanson/d64f2d888dadd128dbd07a2b8fe45cde to your computer and use it in GitHub Desktop.
Alternative to OpenURI for Rails Active Storage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def attach_file(url) | |
with_downloaded_file(url) do |file| | |
my_model.attach(io: file, filename: "filename.jpg") | |
end | |
end | |
# this example requires the 'httparty' gem | |
def with_downloaded_file(url) | |
file = Tempfile.new | |
file.binmode | |
begin | |
file.write HTTParty.get(url).body | |
file.rewind | |
yield file if block_given? | |
ensure | |
file.close | |
file.unlink | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment