Skip to content

Instantly share code, notes, and snippets.

@dnagir
Created April 24, 2013 01:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dnagir/5449012 to your computer and use it in GitHub Desktop.
Save dnagir/5449012 to your computer and use it in GitHub Desktop.
Uploading cloudinary files using DelayedJob without a shared file system. It stores the binary in the database along with DJ and will have some impact on that. So the DJ table needs to be updated to accomodate that (such as making it `UNLOGGED` etc)
module Jobs
class CloudinaryUpload < Struct.new(:uploader_class, :model, :field, :file_name, :content_type, :data)
include Logging
def upload
uploader = uploader_class.new(model, field)
store = Cloudinary::CarrierWave::Storage.new(uploader)
io = Cloudinary::Blob.new(data, original_filename: file_name, content_type: content_type)
uploader.cache!(io)
store.store!(uploader.file)
end
end
end
class FileUploader < CarrierWave::Uploader::Base
include Cloudinary::CarrierWave
class BackgroundStore < Cloudinary::CarrierWave::Storage
def store!(file)
job = Jobs::CloudinaryUpload.new(uploader.class, uploader.model, uploader.mounted_as,
file.original_filename, file.content_type, file.read)
# Ensure no binary data is logged, otherwise it'll clog the log and kill the app
without_query_logging { job.delay.upload }
end
def without_query_logging
prev = ActiveRecord::Base.logger
ActiveRecord::Base.logger = nil
yield
ensure
ActiveRecord::Base.logger = prev
end
end
# Comment this out to disable BG processing
storage BackgroundStore
end
@dnagir
Copy link
Author

dnagir commented Apr 24, 2013

@TalLevAmi would be good to get your feedback on this (alternative to direct uploads).

Maybe you can see a better way of doing it? Specifically I don't like to uploader.cache!(io) but have to do it so that the file data is readily available for the store.store! in carrierwave.

@TalLevAmi
Copy link

Looks like a nice solution in case you don't want to use direct upload.

The advantage of direct uploads is that your backend servers are not involved, which means reduced workload and bandwidth on them.

Regarding cache! alternatives - not really, but if I think of something, I'll let you know.

@dnagir
Copy link
Author

dnagir commented Apr 26, 2013

@TalLevAmi thanks, will be keen to see if you have better ideas.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment