Friday 20 April 2012

process => process in CarrierWave

Well this one is for all those who ever used CarrierWave for uploading there files(no matter which files). Now how many of us had actually extended Carrierwave to process a file (i.e writing you own processing for the file e.g In term of image reducing or increasing the quality of image)

I happen to stumble upon this as all I want was to process a csv file which is suppose to be stored in Amazon S3(on upload) using CarrierWave .

Now the aim was to extract all the information from the CSV (sound simple right ) . Yes it is but I resist the thought of putting the file in Amazon S3 server(first) and then downloading the file and to my server and then extract the data from the CSV file and dump it into database. I want it to be more real time(since the file are small size file) I want user to know that the data in CSV is proper or not and can or cannot data in the CSV can be dumped into database citing validations.

So I realized back when I used to consider PaperClip as my first options, paperclip used to provide me options for processing the file here the link if you want to do it for paperclip Good Luck.

Yes I knew now I have to achieve something of this sort ,but how

Well looking at the uploader file generated by CarrierWave I found out that there is process method ,ok now what how do you apply it.
Inspecting the CarrierWave source code ( for default resize process ) I found out that all you need is to define a method wrapped inside a module .

Now it got it.

So to define a custom processing all you need is to define method wrapped in module and include that module in CarrierWave and pass your process method as an argument to CarrierWave process method define in uploader file
Here how I achieve this.
Inside CarrierWave Uploader
class AssetUploader < CarrierWave::Uploader::Base
   include CarrierWave::CSVProcessor
   process :process_csv
end

That it that all you need to do to define your own file processing.
Just go ahead an define your process_csv method inside module define in file inside config/initializers Voila mission accomplished.
Here how I did it (my file config/initializers/csv_processor.rb)
module CarrierWave
  module CSVProcessor
    def process_csv
      ....
      ....
      ....
    end
  end
end
Go hack now with CarrierWave.

By the way if you want to explore the thought of providing custom error message for CarrierWave here a link that you might want to look at

Hope that it help you in someway or other

No comments:

Post a Comment

What did I learn today?

Welcome to the what did I learn today series. The intention of this blog spot is to compose the stuff that I learnt day-to-day basics and jo...