ruby
45 lines · 7 steps
Deduplicating uploads by content hash
A service that fingerprints each upload with SHA-256 and reuses an existing record when the bytes already exist.
Explained by
highlit
1require "digest"
2
3class UploadDeduplicator
4 CHUNK_SIZE = 64 * 1024
5
6 def initialize(store: UploadDigest)
7 @store = store
8 end
9
10 def register(upload)
11 digest = compute_digest(upload.tempfile.path)
12
13 existing = @store.find_by(sha256: digest)
14 if existing
15 return DuplicateResult.new(duplicate: true, canonical: existing, digest: digest)
16 end
17
18 record = @store.create!(
19 sha256: digest,
20 byte_size: upload.size,
21 content_type: upload.content_type,
22 original_filename: upload.original_filename
23 )
24
25 DuplicateResult.new(duplicate: false, canonical: record, digest: digest)
26 end
27
28 private
29
30 def compute_digest(path)
31 sha = Digest::SHA256.new
32 File.open(path, "rb") do |io|
33 while (chunk = io.read(CHUNK_SIZE))
34 sha.update(chunk)
35 end
36 end
37 sha.hexdigest
38 end
39
40 DuplicateResult = Struct.new(:duplicate, :canonical, :digest, keyword_init: true) do
41 def duplicate?
42 duplicate
43 end
44 end
45end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Content-addressing by cryptographic hash lets you detect identical files regardless of their names or metadata.
- 2Reading a file in fixed-size chunks keeps memory flat no matter how large the upload is.
- 3Injecting the store dependency and returning a small value object keeps the class easy to test and its result explicit.
Related explainers
ruby
class Order class InvalidTransition < StandardError; end TRANSITIONS = {
A state machine for order transitions in Ruby
state-machine
data-driven
error-handling
Intermediate
8 steps
typescript
import { Injectable, UnauthorizedException } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { ExtractJwt, Strategy } from 'passport-jwt'; import { ConfigService } from '@nestjs/config';
How a JWT strategy authenticates in NestJS
authentication
jwt
passport
Intermediate
7 steps
ruby
class CreateOrderItems < ActiveRecord::Migration[7.1] def change create_table :order_items do |t| t.references :order, null: false, foreign_key: { on_delete: :cascade }
Enforcing order-item integrity in Rails
migrations
foreign-keys
validations
Intermediate
7 steps
ruby
class Registration < ApplicationRecord belongs_to :event validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }
Validating registrations in Rails
validations
i18n
error-handling
Intermediate
8 steps
python
import os from datetime import timedelta
Class-based config in a Flask app factory
configuration
app-factory
inheritance
Intermediate
7 steps
ruby
class ApacheLogParser LINE_PATTERN = /\A(?<ip>\S+)\s\S+\s\S+\s\[(?<time>[^\]]+)\]\s"(?<method>[A-Z]+)\s(?<path>\S+)\s(?<protocol>[^"]+)"\s(?<status>\d{3})\s(?<bytes>\d+|-)/ TIME_FORMAT = "%d/%b/%Y:%H:%M:%S %z"
Parsing Apache logs with named captures
regex
named-captures
parsing
Intermediate
6 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/deduplicating-uploads-by-content-hash-explained-ruby-0350/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.