Search code examples
ruby-on-railscarrierwavefog

Dynamic store dirs for same models with carrierwave


I am using CarrierWave with fog to upload my images to S3.

I have model Image that can represent images of different sizes and according to that needs to be saved in different folder.

For example, for image.jpg I could have two different uploaded versions that need to be saved as:

'images/large/image.jpg'
'images/small/image.jpg'

There could be arbitrary number of use cases and versions using minimagick can't cover them all.

So far I haven't been able to find solution. Does anyone know how to do this?


Solution

  • I've seen this question asked a few times so I'll write what my final solution is.

    Instead of defining mount_uploader on model I decided to just use Uploader independently and save urls to records later.

    Dynamically changing store_dir and filename can be accomplished like this

    uploader = Uploader.new
    
    uploader.define_singleton_method(:store_dir) do
        'new_store_dir'
    end
    uploader.define_singleton_method(:filename) do
        'new_filename'
    end
    
    uploader.store!(image)
    

    Using this approach you can also define names with local variables or whatever you have available in controller.

    Hopefully it helps someone else as well.