Skip to content

Instantly share code, notes, and snippets.

@westonganger
Created February 10, 2017 17:53
Show Gist options
  • Save westonganger/6d6c32eaab613bf5dd10f8eb48785485 to your computer and use it in GitHub Desktop.
Save westonganger/6d6c32eaab613bf5dd10f8eb48785485 to your computer and use it in GitHub Desktop.
CarrierWave Uploader thats Compatible with Paperclip fields
class FileUploader < CarrierWave::Uploader::Base
### This uploader is setup for paperclip compatibility
include CarrierWave::MiniMagick
storage :file
def store_dir
"system/#{model.class.to_s.pluralize.underscore}/#{mounted_as.to_s.pluralize}/#{model_id_partition}"
end
def default_url
"/img/diagrams/#{version_name}/missing.png"
end
def version_name
super || :original
end
def full_filename(for_file)
super(for_file).sub("#{version_name}_", '').prepend("#{version_name}/")
end
with_options if: :is_imageable? do
version :thumb do
process resize_to_fit: [50, 64]
process convert: :jpg
def full_filename(for_file)
super(for_file).chomp(File.extname(super(for_file))) + ".jpg"
end
end
version :preview do
process resize_to_fit: [480, 620]
process convert: :jpg
def full_filename(for_file)
super(for_file).chomp(File.extname(super(for_file))) + ".jpg"
end
end
end
# def extension_whitelist
# %w(jpg jpeg gif png)
# end
IMAGE_TYPES = ['jpg','jpeg','png','gif','tif','bmp'].freeze
IMAGEABLE_TYPES = (IMAGE_TYPES + ['pdf']).freeze
private
def is_imageable?(file)
IMAGEABLE_TYPES.include?(file.extension.downcase)
end
# http://over9000.org/rails/paperclip-with-more-than-32-000-attachments
# e.g.: 1234 => "000/001/234"
def model_id_partition
("%09d" % model.id).scan(/\d{3}/).join("/")
end
end
require 'carrierwave/orm/activerecord'
CarrierWave.configure do |config|
config.cache_dir = Rails.root.join('tmp/uploads')
end
class Model < ActiveRecord::Base
mount_uploader :document, Fileuploader, mount_on: :document_file_name
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment