Will
Will

Reputation: 4693

Download an active Storage attachment to disc

The guide says that I can save an attachment to disc to run a process on it like this:

message.video.open do |file|
  system '/path/to/virus/scanner', file.path
  # ...
end

My model has an attachment defined as:

has_one_attached :zip

And then in the model I have defined:

def process_zip      
  zip.open do |file|
    # process the zip file
  end
end

However I am getting an error :

private method `open' called

on the zip.open call.

How can I save the zip locally for processing?

Upvotes: 10

Views: 6193

Answers (2)

ldl
ldl

Reputation: 523

As an alternative in Rails 5.2 you can do this:

def process_zip      
   # Download the zip file in temp dir
   zip_path = "#{Dir.tmpdir}/#{zip.filename}"
   File.open(zip_path, 'wb') do |file|
       file.write(zip.download)
   end   

   Zip::File.open(zip_path) do |zip_file|  
       # process the zip file
       # ...
       puts "processing file #{zip_file}"
   end
end

Upvotes: 13

George Claghorn
George Claghorn

Reputation: 26535

That’s an edge guide (note edgeguides.rubyonrails.org in the URL); it applies to the master branch of the rails/rails repository on GitHub. The latest changes in master haven’t been included in a released version of Rails yet.

You’re likely using Rails 5.2. Use edge Rails to take advantage of ActiveStorage::Blob#open:

gem "rails", github: "rails/rails"

Upvotes: 1

Related Questions