Skip to content

Instantly share code, notes, and snippets.

@waclock
Created September 3, 2019 16:01
Show Gist options
  • Save waclock/ff8144577ea057007284400f34711706 to your computer and use it in GitHub Desktop.
Save waclock/ff8144577ea057007284400f34711706 to your computer and use it in GitHub Desktop.
Base Shrine Uploader
# frozen_string_literal: true
require "image_processing/mini_magick"
class BaseUploader < Shrine
ALLOWED_TYPES = %w[image/jpeg image/png image/svg+xml image/gif].freeze
MAX_SIZE = 10 * 1024 * 1024 # 10 MB
plugin :remove_attachment
plugin :pretty_location
plugin :processing
plugin :versions
plugin :validation_helpers
plugin :store_dimensions, analyzer: :mini_magick
plugin :remote_url, max_size: nil
plugin :default_url
plugin :upload_options, store: -> (io, context) do
{ acl: "private" }
end
Attacher.default_url do |_options|
host = if Rails.env.production?
ENV.fetch('PRODUCTION_URL')
elsif Rails.env.staging?
ENV.fetch('STAGING_URL')
else
"http://localhost:3000"
end
class_name = context[:record].class.name.to_s.downcase
"#{host}/assets/defaults/#{class_name}/#{context[:name]}.png"
end
Attacher.validate do
validate_max_size MAX_SIZE
if validate_mime_type_inclusion(ALLOWED_TYPES)
validate_max_width 10_000
validate_max_height 10_000
end
end
def generate_location(io, context)
type = context[:record].class.name.downcase if context[:record]
style = context[:version] == :original ? "originals" : "thumbs" if context[:version]
name = super # the default unique identifier
[style, name].compact.join("/")
end
process(:store) do |io, _context|
original = io.download
thumbnail = ImageProcessing::MiniMagick
.source(original)
.resize_to_limit!(600, nil)
original.close!
{original: io, thumbnail: thumbnail}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment