Search code examples
ruby-on-railsfile-uploadcallbackversioncarrierwave

How do I skip a carrierwave store callback when processing versions


I have a callback defined in my video uploader class of carrierwave
after :store, :my_method
and I have three versions of the files. original,standard,low

my_method executes when each version is processed ie, three times, I just need the callback to execute once.


Solution

  • I know this is a very late response but I was just having the same problem lately so I decided to post how I solved this "problem" since it seems it isn't documented on carrierwave's github page (or I wasn't able to find it anyway).

    Ok, regarding the after :store, :my_method callback if you place it in the "main body" of your uploader class, then it's going to be executed every single time a file is stored, so in your case I think it even executes not only for your 3 versions but for your original file as well.

    Let's say the following code defines your carrierwave uploader:

    class PhotoUploader < CarrierWave::Uploader::Base
      after :store, :my_method
    
      version :original do
        process :resize_to_limit => [1280,960]
      end
    
      version :standard, from_version: :original do
        process :resize_to_limit => [640,480]
      end
    
      version :low, from_version: :standard do
        process :resize_to_limit => [320,240]
      end
    
      protected
        def my_method
          puts self.version_name
        end
    end
    

    That way, the after :store is going to be executed for every file stored, but if you only want it to be executed, let's say, for the :low version, all you have to do is to move that line inside your version definition. Like this:

    class PhotoUploader < CarrierWave::Uploader::Base
    
      version :original do
        process :resize_to_limit => [1280,960]
      end
    
      version :standard, from_version: :original do
        process :resize_to_limit => [640,480]
      end
    
      version :low, from_version: :standard do
        process :resize_to_limit => [320,240]
        after :store, :my_method
      end
    
      protected
        def my_method
          puts self.version_name
        end
    end
    

    I tested it on my code and it works... I know it's been a long time since you posted this question and probably you arrived at the same solution as me. So I decided to answer it for future reference for anyone getting the same problem.