I need to do some post processing on a file upload that isn't images - in paperclip I can have a custom post processor, but I can't find any way to do this in carrierwave.
Ruby 1.9.3, Rails 3.2.7 and CarrierWave 0.6.2.
This gem provides a simple and extremely flexible way to upload files from Ruby applications. It works well with Rack based web applications, such as Ruby on Rails.
Setting Up CarrierWave You need to create an initializer for CarrierWave, which will be used for loading CarrierWave after loading ActiveRecord. Navigate to config > initializers and create a file: carrier_wave. rb. Paste the code below into it.
A file can be uploaded to server in two ways, one we can send the image as base64 string as plain text and another one is using multipart/form-data . The first one is the worst idea as it sends the entire image as plain text.
The OP's question was how to process files which are not images.
Please have a look at this source file on GitHub: carrierwave/lib/carrierwave/uploader/processing.rb and check the comments.
You'll have create your own CarrierWave uploader sub-class and mount it in your model like this:
def MyModel < ActiveRecord::Base
# this is where the uploaded file will be available in your model,
# as a `MyUploader` instance:
#
mount_uploader :uploaded_file, MyUploader
...
end
Please note that it's mounted on the ActiveRecord attribute :uploaded_file
.
This means when you access :uploaded_file
from your model, you will get an instance of your CarrierWave uploader for the particular file which was uploaded.
You can simply define your processing inside your uploader as follows:
class MyUploader < CarrierWave:Uploader::Base
process :my_custom_processing => [param1,param2,param3]
def my_custom_processing(param1,param2,param3)
...
# e.g. you could call a method which is defined elsewhere,
# which operates on a file:
my_nifty_file_processor( self.uploaded_file )
#
# or you could just do this directly:
uploaded_data = self.uploaded_file.read
...
end
end
Inside my_nifty_file_processor
, you would simply call read
on the object that gets passed in to read the file.
CarrierWave lets you call read
on any Uploader instance (= any instance of an uploaded file) and it will read that file.
One more Tip:
Sometimes you need to access the ActiveRecord model within your uploader, for which the file was uploaded.
Simply access it inside your uploader code like this:
self.model
This lets you store additional information about the uploaded file, such as format, directly in your AR model.
I wrote a blog post on how to create custom post-processor to create thumbnails of videos, maybe you will find it useful.
https://prograils.com/posts/video-encoding-processor-for-carrierwave/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With