module Shrine::Plugins::Signature

  1. lib/shrine/plugins/signature.rb

The signature plugin provides the ability to calculate a hash from file content. The hash can then be used as a checksum or just as a unique signature of the file.

plugin :signature

The plugin adds a calculate_signature instance and class method to Shrine, which accepts the IO object and hashing algorithm and returns the calculated hash.

Shrine.calculate_signature(io, :md5)
#=> "9a0364b9e99bb480dd25e1f0284c8555"

You can then use the add_metadata plugin to add a new metadata field with the calculated hash.

plugin :add_metadata

add_metadata :md5 do |io, context|
  calculate_signature(io, :md5)
end

This will generate a hash for each uploaded file, but if you want to generate one only for the original file, you can add a conditional:

add_metadata :md5 do |io, context|
  calculate_signature(io, :md5) if context[:action] == :cache
end

The following hashing algorithms are supported:

  • sha1

  • sha256

  • sha384

  • sha512

  • md5

  • crc32

You can also choose which format will the calculated hash be encoded in:

Shrine.calculate_signature(io, :md5, format: :hex)

The following encoding formats are supported:

  • none

  • hex (default)

  • base64

Constants

SUPPORTED_ALGORITHMS = SignatureCalculator::SUPPORTED_ALGORITHMS  
SUPPORTED_FORMATS = SignatureCalculator::SUPPORTED_FORMATS