module Shrine::Plugins::InferExtension

  1. lib/shrine/plugins/infer_extension.rb

The infer_extension plugin allows deducing the appropriate file extension for the upload location based on the MIME type of the file. This is useful when using data_uri and remote_url plugins, where the file extension might not be known.

plugin :infer_extension

Ordinarily, the upload location will gain the inferred extension only if it couldn't be determined from the filename. However, you can pass force: true to force the inferred extension to be used rather than an extension from the original filename. This can be used to canonicalize extensions (jpg, jpeg => jpeg), or replace an incorrect original extension.

plugin :infer_extension, force: true

By default MIME::Types will be used for inferring the extension, but you can also choose a different inferrer:

plugin :infer_extension, inferrer: :mini_mime

The following inferrers are accepted:

:mime_types

(Default). Uses the mime-types gem to infer the appropriate extension from MIME type.

:mini_mime

Uses the mini_mime gem to infer the appropriate extension from MIME type.

You can also define your own inferrer, with the possibility to call the built-in inferrers:

plugin :infer_extension, inferrer: -> (mime_type, inferrers) do
  # don't add extension if the file is a text file
  inferrers[:rack_mime].call(mime_type) unless mime_type == "text/plain"
end

You can also use methods for inferring extension directly:

Shrine.infer_extension("image/jpeg")
# => ".jpeg"

Shrine.extension_inferrers[:mime_types].call("image/jpeg")
# => ".jpeg"

Methods

Public Class

  1. configure

Public Class methods

configure (uploader, opts = {})
[show source]
# File lib/shrine/plugins/infer_extension.rb, line 55
def self.configure(uploader, opts = {})
  uploader.opts[:infer_extension_inferrer] = opts.fetch(:inferrer, uploader.opts.fetch(:infer_extension_inferrer, :mime_types))
  uploader.opts[:infer_extension_force] = opts.fetch(:force, uploader.opts.fetch(:infer_extension_force, false))
end