require 'digest' class MaterialFileSha256 def self.from_blob blob, allow_download: false sha256 = blob.metadata['sha256'] return sha256 if sha256.present? return nil unless allow_download begin blob.open do |file| sha256 = Digest::SHA256.file(file.path).hexdigest blob.metadata['sha256'] = sha256 blob.save! if blob.changed? sha256 end rescue ActiveStorage::FileNotFoundError, ArgumentError => error Rails.logger.warn( "MaterialFileSha256.from_blob failed for blob_id=#{blob.id}: " \ "#{error.class}: #{error.message}", ) nil end end def self.from_upload upload tempfile = upload&.tempfile return nil unless tempfile tempfile.rewind Digest::SHA256.file(tempfile.path).hexdigest.tap do tempfile.rewind end end end