Search code examples
ruby-on-railsrails-activestorage

Download file in service object with ActiveStorage


A user uploads a document and this gets stored in Azure with ActiveStorage. The next step is that the backend processes this and therefore I have a service object to do this. So I need to download the file from Azure to the tmp folder within the Rails app. How do I download the file? I cannot use rails_blob_url because it is not available in a service object, only in controllers and views.

When I still used Paperclip I did something like this:

require 'open-uri'
file = Rails.root.join('tmp', user.attachment_file_name)
name = user.attachment_file_name
download = open(user.attachment.url)
download_result = IO.copy_stream(download, file)

How can I do something similar with ActiveStorage?


Solution

  • You can use ActiveStorage::Blob#open:

    Downloads the blob to a tempfile on disk. Yields the tempfile.

    Given this example from the guides:

    class User < ApplicationRecord
      has_one_attached :avatar
    end
    

    You can do this with:

    user.avatar.open do |tempfile|
      # do something with the file
    end
    

    If its has_many_attached you of course need to loop through the attachments.

    See: