Skip to content

Instantly share code, notes, and snippets.

@stevehanson
Last active August 1, 2019 13:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevehanson/d64f2d888dadd128dbd07a2b8fe45cde to your computer and use it in GitHub Desktop.
Save stevehanson/d64f2d888dadd128dbd07a2b8fe45cde to your computer and use it in GitHub Desktop.
Alternative to OpenURI for Rails Active Storage

Ruby's OpenURI is dangerous and should not be used in production. This is an alternative.

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