Created
February 20, 2022 12:18
-
-
Save nejdetkadir/0a74f1f418e7cd180fca6eb211497d5b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
class ImageUploader < CarrierWave::Uploader::Base | |
# Include RMagick or MiniMagick support: | |
# include CarrierWave::RMagick | |
include CarrierWave::MiniMagick | |
# Choose what kind of storage to use for this uploader: | |
storage :file | |
# storage :fog | |
# Override the directory where uploaded files will be stored. | |
# This is a sensible default for uploaders that are meant to be mounted: | |
def store_dir | |
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" | |
end | |
# Provide a default URL as a default if there hasn't been a file uploaded: | |
# def default_url(*args) | |
# # For Rails 3.1+ asset pipeline compatibility: | |
# # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_')) | |
# | |
# "/images/fallback/" + [version_name, "default.png"].compact.join('_') | |
# end | |
# Create different versions of your uploaded files: | |
version :small, if: :image? do | |
process resize_to_fit: [100, 100] | |
end | |
version :medium, if: :image? do | |
process resize_to_fit: [500, 500] | |
end | |
version :large, if: :image? do | |
process resize_to_fit: [100, 100] | |
end | |
# Add an allowlist of extensions which are allowed to be uploaded. | |
# For images you might use something like this: | |
def extension_allowlist | |
%w[jpg jpeg png webp mp4 avi webm] | |
end | |
def content_type_allowlist | |
%w[image/jpg image/jpeg image/png image/webp video/mp4 video/x-msvideo video/webm] | |
end | |
def size_range | |
1.byte..10.megabytes | |
end | |
# Override the filename of the uploaded files: | |
# Avoid using model.id or version_name here, see uploader/store.rb for details. | |
def filename | |
"#{secure_token}.#{file.extension}" if original_filename.present? | |
end | |
protected | |
def secure_token | |
var = :"@#{mounted_as}_secure_token" | |
model.instance_variable_get(var) or model.instance_variable_set(var, SecureRandom.uuid) | |
end | |
def image?(file) | |
file.content_type.start_with? 'image' | |
end | |
def video?(file) | |
status = file.content_type.start_with? 'video' | |
model.content_type = :video if status | |
status | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment