Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 442
Will Avatar asked May 25 '18 12:05

Will


People also ask

Where are active storage images stored?

By default in the development environment, Active Storage stores all uploaded images on your local disk in the storage subdirectory of the Rails application directory. That's the file you uploaded!

What is meant by active storage?

1 What is Active Storage? Active Storage facilitates uploading files to a cloud storage service like Amazon S3, Google Cloud Storage, or Microsoft Azure Storage and attaching those files to Active Record objects.

How does active storage work in Rails?

Active Storage uses two tables in your application's database named active_storage_blobs and active_storage_attachments . After creating a new application (or upgrading your application to Rails 5.2), run rails active_storage:install to generate a migration that creates these tables.


2 Answers

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
like image 166
ldl Avatar answered Oct 08 '22 01:10

ldl


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"
like image 22
George Claghorn Avatar answered Oct 08 '22 00:10

George Claghorn