michalvalasek
michalvalasek

Reputation: 1573

Store two versions of a file at once using Carrierwave

I'm using Carrierwave and Fog gems to store a file to my Amazon S3 bucket (to /files/file_id.txt). I need to store a slightly different version of the file to a different location in the bucket (/files/file_id_processed.txt) at the same time (right after the original is stored). I don't want to create a separate uploader attribute for it on the model - is there any other way?

This my current method that stores the file:

def store_file(document)
  file_name = "tmp/#{document.id}.txt"

  File.open(file_name, 'w') do |f|
    document_content = document.content
    f.puts document_content
    document.raw_export.store!(f)
    document.save
  end

  # I need to store the document.processed_content

  File.delete(file_name) if File.exist?(file_name)
end

This is the Document model:

class Document < ActiveRecord::Base
  mount_uploader :raw_export, DocumentUploader
  # here I want to avoid adding something like:
  # mount_uploader :processed_export, DocumentUploader
end

This is my Uploader class:

class DocumentUploader < CarrierWave::Uploader::Base

  storage :fog

  def store_dir
    "files/"
  end

  def extension_white_list
    %w(txt)
  end
end

Upvotes: 0

Views: 326

Answers (2)

michalvalasek
michalvalasek

Reputation: 1573

This is how my final solution looks like (kinda) - based on Nitin Verma's answer:

I had to add a custom processor method for the version to the Uploader class:

# in document_uploader.rb

...

version :processed do
  process :do_the_replacements
end

def do_the_replacements
  original_content = @file.read
  File.open(current_path, 'w') do |f|
    f.puts original_content.gsub('Apples','Pears')
  end
end

Upvotes: 1

Nitin
Nitin

Reputation: 7366

considering that you need similar file but with different name. for this you need to create a version for file in uploader.

version :processed do
  process
end

and now second file name will be processed_{origional_file}.extension. if you want to change file name of second file you can use this link https://github.com/carrierwaveuploader/carrierwave/wiki/How-to:-Customize-your-version-file-names

Upvotes: 0

Related Questions