Want to know the future location of a file upload? Want fast responses by moving file uploads into a background task with something like Sidekiq? Building an API and you want to immediately tell the client where the upload is going to be before actually uploading the file? Then try the tweaks below. This is definitely a monkey patch - mileage may vary.
class PhotoUploader < CarrierWave::Uploader::Base
# Note:You've got to be using this option for the magic to work. It's
# used by default, though, so you should be fine unless you commented
# it out.
#
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
# New Method - the magic
#
# Note: I'm using Cloudfront as an asset host, you may need to swap out
# #{asset_host} with a different uploader instance method based on
# your setup.
#
def future_url(version = nil) # you can pass in versions here, either as a string or as a symbol
filename = [version.to_s, base_filename].compact.reject(&:empty?).join('_')
"#{asset_host}/#{store_dir}/#{filename}"
end
# Adjust this method.
#
# Note:You've got to be using this option (commented out
# by default) for the magic to work.
#
def filename
base_filename if original_filename
end
# New Method
def base_filename
"photo.jpg"
end
end
# Usage
u = User.last
u.photo.future_url #=> https://12345efdt6789.cloudfront.net/uploads/user/photo/999/photo.jp
u.photo.future_url(:thumb) #=> https://12345efdt6789.cloudfront.net/uploads/user/photo/999/thumb_photo.jp