CarrierWave Process Parameters (or: MakeIt800.com, Casualty of the Zeitgeist)
I have an idea for a new app, MakeIt800.com! Users can upload any photo and receive a copy scaled to an 800-pixel square, for optimum convenience.
I want to build my fledgling empire on Rails, and upload my photos with CarrierWave:
class PhotoUploader < CarrierWave::Uploader::Base
process resize_to_fill: [800, 800]
end
Awesome, app done, legacy secured.
Later that afternoon, one of the interns interrupts my sun-bathing to brag about her weekend project, square.it — an app that processes photos into squares of any size, with futuristic URLs like square.it/800, or even square.it/900!
After brief consideration of legal action, I resolve to overcome my opponent with sheer superiority. But how has she accomplished this? CarrierWave doesn’t seem to allow me to pass parameters from a route into an uploader’s processes!
The intern I wrangled for this work had some notes:
# Storing the parameters on the uploader isn’t great, but
# it’s better than putting them on the modelclass PhotoUploader < CarrierWave::Uploader::Base
attr_accessor :size process resize_to_fill: [@size, @size]
end
# Note that we need to set our new uploader values AFTER
# the model is initialized, but BEFORE we trigger
# CarrierWave’s processingclass ConversionsController < ApplicationController
def create
conversion = Conversion.new
conversion.photo.size = params[:size] # ← Right here!
conversion.photo = params[:photo] # ...
end
end
# For a custom process (maybe with many parameters), we can
# move the processing and parameters into a separate moduleclass PhotoUploader < CarrierWave::Uploader::Base
include AlterImage
endmodule AlterImage
extend ActiveSupport::Concern attr_accessor :a, :b, :c, :d included do
process :my_custom_alteration
end private def my_custom_alteration
# ...
end
end
# Testing fixtures or factories that rely on our process
# will also need to keep these operations in the right orderFactoryGirl.define do
factory :conversion do
before(:create) do |instance|
instance.photo.size = 800
instance.photo = photo_fixture
end # ...
end
end
Now — I’m not sure what any of that means, but I’ve been assured that make.it/800 debuts tomorrow!