Andrey Skuratovsky
Andrey Skuratovsky

Reputation: 687

Rails carrierwave mounting on condition

I need to mount picture uploader after some verification function.

But if I call as usual mounting uploader in model:

mount_uploader :content, ContentUploader

carrierwave first download content, and then Rails start verification of model.

Specifically, I don't want to load big files at all! I want to check http header Content-length and Content-type and then, if it's OK, mount uploader.

Maybe something like that:

if condition
  mount_uploader :content, ContentUploader
end

How can I do it?

P.S. Rails version 3.2.12

Upvotes: 4

Views: 969

Answers (1)

Djunzu
Djunzu

Reputation: 498

This is not the way to go if you just want avoid loading big files! That said, one can have conditional mount overriding content=.

As CarrierWave v1.1.0 there is still no conditional mount. But note that mount_uploader first includes a module in the class and then overrides the original content= to call the method content= defined in the included module. So, a workaround is just to redefine the accessors after you have called mount_uploader:

class YourModel < ActiveRecord::Base
    mount_uploader :content, ContentUploader

    def content=(arg)
        if condition
            super
        else
            # original behavior
            write_attribute(:content, arg)
        end
    end

    def content
        # some logic here
    end
end

Upvotes: 1

Related Questions