Marten Rails Bridge
Library designed to help Marten projects interoperate with Rails-managed data, signed payloads, and selected Rails-owned tables while both applications run in parallel.
API documentation: https://miry.codeberg.page/marten-rails-bridge/index.html
Scope
This shard focuses on narrow, explicit Rails compatibility for Marten. It is not a Rails port and it is not intended to reproduce all of Active Record or Rails internals.
In scope:
- Rails-compatible cryptographic primitives used by Marten apps
- Signed payloads, signed IDs, and SGID-related helpers
- Compatibility layers for selected Rails-owned tables, starting with ActiveStorage and ActionText
- Small, opt-in entrypoints so a Marten app can load only the Rails-compatible features it needs
Out of scope:
- Full Rails or Active Record reimplementation
- Migrations, schema ownership, or database lifecycle tooling
- Rails controllers, jobs, views, helpers, or generic engine support
Features
- [ ] ActiveRecord field encryption
- [ ] ActiveStorage blob and attachment URL generation
- [x] Upload a file to a service and write its blob row (
Blob.create_and_upload!) - [x] Serve a blob through the app with the proxy endpoint, range requests included
- [ ] Support :uuid for primary key
- [ ] Support non standard table name
- [x] Upload a file to a service and write its blob row (
- [x] ActionText::RichText rendering and persistence (partial)
- [x] Rich text rendering to HTML fragments
- [x] Basic image embed rendering for
action-text-attachment - [x] Record associations via
record_type,record_id,name - [ ] Full Rails ActionText + ActiveStorage feature parity
- [ ] signed message verification helpers
- [x] SignedGlobalID generation, verification, and locate helpers
- [ ] reusable signed ID helpers for Marten models
- [ ] Marten-facing configuration API for shared secrets and encryption keys
- [x] Read the Rails credentials config and use it for encryption keys
- [x]
config/credentials.yml.encand per-environment files, read and written - [x]
Rails.load_secrets!: one call configures every secret from the credentials - [ ]
Marshalpayloads other than aString
- [x]
Usage
Version
require "marten_rails_bridge"
MartenRailsBridge::VERSION
Rails credentials
Read the Rails application's config/credentials.yml.enc and configure every secret in this shard
from it. One call, and no secret copied into Marten's settings:
# config/initializers/credentials.cr
require "marten_rails_bridge/rails/secrets"
# The Rails application root: the directory holding `config/`.
Rails.root = "../my_rails_app"
Rails.load_secrets!
That sets:
ActiveSupport::KeyGenerator.instance, fromsecret_key_base, with the 1000 PBKDF2 iterations Rails uses — so every signature this shard produces and accepts matches Rails'SignedGlobalID.verifier, from thesigned_global_idskey, signed with SHA-1ActiveRecord::Encryption.primary_key,#deterministic_keyand#key_derivation_saltfrom theactive_record_encryptionentry, and rebuilds the three ciphers
The Active Record keys are left alone when the credentials carry no active_record_encryption
entry. Pass Rails.load_secrets!(active_record_encryption: false) to skip them even when they are
there.
Wrong or missing secrets raise rather than falling back to an empty one, since a signature made
with the wrong key reads as a 404 from an endpoint that otherwise looks fine:
| what happened | what is raised |
| --------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- |
| no secret_key_base anywhere, outside development and test | Rails::MissingSecretKeyBaseError |
| a secret is in the file but is not a string, usually an unquoted all-digit one that YAML read as a number | Rails::InvalidCredentialError |
| the key is not 32 hexadecimal characters | ActiveSupport::EncryptedFile::InvalidKeyLengthError |
| the key is missing and raise_if_missing_key is set | ActiveSupport::EncryptedFile::MissingKeyError |
| the file does not decrypt with the key | ActiveSupport::MessageEncryptor::InvalidMessage |
Quote any secret made only of digits, or YAML hands back a number and the key is refused:
secret_key_base: "1234567890123456"
Reading values
Rails.credentials.read # => "secret_key_base: abc\n..."
Rails.credentials["secret_key_base"] # => raises KeyError when absent
Rails.credentials["secret_key_base"]? # => nil when absent
Rails.credentials.secret_key_base # => nil when absent
Rails.credentials.secret_key_base! # => raises KeyError when absent
Rails.credentials.dig("aws", "access_key_id") # => raises when absent
Rails.credentials.dig?("aws", "access_key_id") # => nil when absent
Rails.encrypted("config/my_config.enc").read # any other encrypted file
Values come back as YAML::Any, so #as_s, #as_i and friends are how you reach the underlying
type. Crystal has no runtime method_missing, so Rails.credentials.secret_key_base comes from a
macro and only reaches the first level — use #dig for anything nested.
Which file, which key
The same rules Rails follows, so the two never disagree:
| | Rails and this shard |
| ----------------- | ------------------------------------------------------------------------------------------------------------ |
| file | config/credentials/<env>.yml.enc when it exists, else config/credentials.yml.enc |
| key | ENV["RAILS_MASTER_KEY"], then config/credentials/<env>.key when it exists, else config/master.key |
| environment | RAILS_ENV, then RACK_ENV, then development |
| secret_key_base | ENV["SECRET_KEY_BASE"], then the credentials, then tmp/local_secret.txt in development and test only |
| cipher | aes-128-gcm — note this is not the aes-256-gcm of ActiveRecord::Encryption |
| envelope | Base64(ciphertext)--Base64(iv)--Base64(auth_tag) |
| payload | Marshal.dump(yaml), not the YAML text |
The file and the key fall back independently, so a per-environment credentials file encrypted with
the shared config/master.key still reads.
Writing and editing
#write replaces the file in one rename, after checking that what it just encrypted decrypts
back to what was handed in — this file holds every secret an application has, and a write that
cannot be read back would otherwise surface on the next deploy.
#edit decrypts to a 0600 file under the system temporary directory, never next to
credentials.yml.enc, runs $EDITOR, writes back, and deletes the plaintext even when the editor
raises. Nothing is written when the editor exits non-zero or leaves the content unchanged.
Rails.credentials.write("secret_key_base: #{Random::Secure.hex(64)}\n")
Rails.credentials.edit # $EDITOR
Rails.credentials.edit("code -w")
A bin/rails credentials:* equivalent is in examples/credentials.cr:
crystal run examples/credentials.cr -- --root=../my_rails_app init
crystal run examples/credentials.cr -- --root=../my_rails_app show
crystal run examples/credentials.cr -- --root=../my_rails_app get aws access_key_id
crystal run examples/credentials.cr -- --root=../my_rails_app edit
Check against Rails with bin/rails credentials:show. A file written here reads there, and the
other way round.
ActiveSupport::KeyGenerator
Configuring the secrets by hand, instead of reading them from the credentials above.
To use with ActiveStorage or ActiveRecord::Encryption,
initialize ActiveSupport::KeyGenerator with your application's
secret_key. If you are sharing a database with a Rails application,
you can also use the Rails app SECRET_KEY_BASE.
See: https://guides.rubyonrails.org/security.html#secret-session-store
# config/initializers/key_generator.cr
require "marten_rails_bridge/active_support/key_generator"
# Use SECRET_KEY_BASE from Rails app or Marten's secret_key (defaults to MARTEN_SECRET_KEY env var)
ActiveSupport::KeyGenerator.instance =
ActiveSupport::KeyGenerator.new(ENV["SECRET_KEY_BASE"]? || Marten.settings.secret_key, iterations: 1000)
To get SECRET_KEY_BASE from your Rails app:
bin/rails runner "puts Rails.application.secret_key_base"
or
bin/rails runner "puts Rails.application.credentials[:secret_key_base]"
Verify the correctness with:
bin/rails runner 'puts Rails.application.key_generator.generate_key("active_record/signed_id").bytes.inspect'
It should be similar with output from:
crystal run examples/key_generator.cr -- --key="<key>" "active_record/signed_id"
ActiveSupport::MessageVerifier
ActiveSupport::MessageVerifier can generate Rails-compatible signed payloads
for IDs and structured values.
require "marten_rails_bridge/active_support/message_verifier"
secret = ActiveSupport::KeyGenerator.instance.generate_key("ActiveStorage")
verifier = ActiveSupport::MessageVerifier.new(secret, algorithm: OpenSSL::Algorithm::SHA1)
verifier.generate(19, purpose: "blob_id")
# => "<base64-json>--<hex-digest>"
You can also include an absolute expiration timestamp, which is encoded as Rails-style metadata (_rails.exp):
expires_at = Time.utc + 15.minutes
verifier.generate("gid://drar/ActiveStorage::Blob/21", purpose: "blob_id", expires_at: expires_at)
Note: expires_in convenience support is currently implemented in SignedGlobalID, not directly in ActiveSupport::MessageVerifier.
SignedGlobalID
SignedGlobalID provides Rails-compatible signed gid://... values with purpose and expiration checks.
require "marten_rails_bridge/active_support/key_generator"
require "marten_rails_bridge/active_support/message_verifier"
require "marten_rails_bridge/global_id/signed_global_id"
ActiveSupport::KeyGenerator.instance =
ActiveSupport::KeyGenerator.new(ENV.fetch("SECRET_KEY_BASE"), iterations: 1000)
secret = ActiveSupport::KeyGenerator.instance.generate_key("signed_global_ids")
SignedGlobalID.verifier = ActiveSupport::MessageVerifier.new(secret, algorithm: OpenSSL::Algorithm::SHA1)
sgid = SignedGlobalID.create("gid://drar/ActiveStorage::Blob/21", purpose: "blob_id").to_s
parsed = SignedGlobalID.parse(sgid, purpose: "blob_id")
# => SignedGlobalID or nil when signature/purpose/expiration is invalid
Locate any record with a block resolver:
record = SignedGlobalID.locate(sgid, purpose: "blob_id") do |app, model_name, model_id, params|
next nil if app != "drar" || model_name != "ActiveStorage::Blob"
ActiveStorage::Blob.get(id: model_id)
end
Configuration requirements:
- Set
ActiveSupport::KeyGenerator.instancewith the same base secret as Rails (SECRET_KEY_BASE) - Use the same verifier key derivation salt and algorithm as Rails for exchanged SGIDs (
ActiveStorageuses SHA1)
Intentional deviations from upstream globalid:
- No built-in locator registry yet (
SignedGlobalID.locateis block-based) SignedGlobalID.createcurrently acceptsgidstrings/URIs, not model instances
Runnable example:
crystal run examples/signed_global_id.cr -- --secret-key-base="<SECRET_KEY_BASE>" --purpose="attachable" --gid="gid://drar/ActiveStorage::Blob/13?expires_in"
ActiveRecord::Encryption
Rails.load_secrets! already sets these three keys from the active_record_encryption entry of
the credentials — see Rails credentials. Configure them by hand only when
they do not live there:
# config/initializers/active_record.cr
require "marten_rails_bridge/active_record/encryption.cr"
require "./key_generator"
ActiveRecord::Encryption.primary_key = ENV.fetch("ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY", "11111111111111111111111111111111")
ActiveRecord::Encryption.deterministic_key = ENV.fetch("ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY", "22222222222222222222222222222222")
ActiveRecord::Encryption.key_derivation_salt = ENV.fetch("ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT", "33333333333333333333333333333333")
# The keys above should match your Rails application's encryption settings.
# See Rails guides for configuration:
# - https://guides.rubyonrails.org/active_record_encryption.html
# - https://api.rubyonrails.org/classes/ActiveRecord/Encryption/Config.html
#
# - primary_key: Rails `active_record_encryption.primary_key` (from credentials/secrets)
# - deterministic_key: Rails `active_record_encryption.deterministic_key`
# - key_derivation_salt: Rails `active_record_encryption.key_derivation_salt` (defaults to "ActiveRecord Encryption")
#
# To get or set keys in your Rails app, use one of:
# bin/rails credentials:edit # Add/edit active_record_encryption in credentials
# bin/rails console # Then run: Rails.application.credentials[:active_record_encryption]
# bin/rails runner "puts Rails.application.credentials[:active_record_encryption]" # Alternative
#
ActiveRecord::Encryption.encryptor = ActiveRecord::Encryption::Encryptor.new
ActiveRecord::Encryption.primary_cipher = ActiveRecord::Encryption::Cipher.new(secret: ActiveRecord::Encryption.primary_encryption_key)
ActiveRecord::Encryption.primary_sha1_cipher = ActiveRecord::Encryption::Cipher.new(secret: ActiveRecord::Encryption.primary_sha1_encryption_key)
ActiveRecord::Encryption.deterministic_cipher = ActiveRecord::Encryption::Cipher.new(secret: ActiveRecord::Encryption.deterministic_encryption_key)
After the encryption system is configured, it can be used with Marten::Model.
Currently the integration is manual, since it is not yet fully integrated with a Marten custom field type.
For example, in Rails you might define an encrypted model like this:
class User
encrypts :name
encrypts :email, deterministic: true
end
The equivalent model in Marten would look something like this:
class User < Marten::Model
db_table :users
field :id, :big_int, primary_key: true, auto: true
field :name, :string, max_size: 510, null: true, blank: true
field :email, :string, max_size: 255, null: true, blank: true
def name_decoded
self.class.decrypt(name, deterministic: false)
end
def name_encode(value : String)
self.name = self.class.encrypt(value, deterministic: false)
end
def email_decoded
self.class.decrypt(email, deterministic: true)
end
def email_encode(value : String)
self.email = self.class.encrypt(value, deterministic: true)
end
def self.find_by_email(email)
encrypted = encrypt(email, deterministic: true)
filter(email: encrypted).all
end
def self.encrypt(value : String, deterministic : Bool) : String
ActiveRecord::Encryption.encryptor.encrypt(value, deterministic: deterministic)
end
def self.decrypt(value : String?, deterministic : Bool)
return nil if value.nil? || value.empty?
ActiveRecord::Encryption.encryptor.decrypt(value, deterministic: deterministic)
rescue ex : ActiveRecord::Encryption::Error
Log.error(exception: ex) { "Could not decrypt value: #{value}" }
nil
end
end
In this example, encrypted values are stored directly in the database fields (name, email),
and helper methods are used to return the decrypted values.
Checkout the examples/demo for full example of usage.
ActiveStorage
This shard maps Rails ActiveStorage tables to Marten models:
ActiveStorage::Blob->active_storage_blobsActiveStorage::Attachment->active_storage_attachments
1. Configure Host And Services
# config/initializers/activestorage.cr
require "marten_rails_bridge/active_storage/service"
require "marten_rails_bridge/active_storage/service/disk_service"
require "marten_rails_bridge/active_storage/service/s3_service"
# Host of your Rails app that serves /rails/active_storage/* redirect endpoints
ActiveStorage::Blob.host = "http://localhost:3000"
ActiveStorage::Blob.services = {
"digitalocean" => ActiveStorage::Service::S3Service.new(
endpoint: "https://fra1.digitaloceanspaces.com",
access_key_id: ENV.fetch("DIGITALOCEAN_ATTACHMENTS_ACCESS_KEY_ID", "admin"),
secret_access_key: ENV.fetch("DIGITALOCEAN_ATTACHMENTS_SECRET_ACCESS_KEY", "password"),
bucket: "app-storage",
region: "unused"
),
"s3" => ActiveStorage::Service::S3Service.new(
endpoint: "http://127.0.0.1:9000",
access_key_id: "admin",
secret_access_key: "password",
bucket: "storage",
region: "us-east-1",
force_path_style: true
),
# Files stored on the local filesystem, like the Rails `local` service
"local" => ActiveStorage::Service::DiskService.new(
root: "storage"
),
} of String => ActiveStorage::Service
Use the same service names and the same root as your Rails app. The root is the directory
config/storage.yml points at. A blob with the key gz0zdzhk0yn6zjhxfzl6qt1ys5rj is stored in
storage/gz/0z/gz0zdzhk0yn6zjhxfzl6qt1ys5rj, as Rails stores it.
2. Add ActiveStorage Accessors To Your Model
require "marten_rails_bridge/active_storage/attachment"
require "marten_rails_bridge/active_storage/blob"
class User < Marten::Model
db_table :users
def avatar_attachment
ActiveStorage::Attachment.filter(record_type: "User", record_id: id, name: "avatar").first
end
@avatar_blob : ActiveStorage::Blob?
def avatar_blob
@avatar_blob ||= avatar_attachment.try &.blob
end
end
3. Create Blob/Attachment Records
Use .create_and_upload! to store a file in a service and write its row in one call:
user = User.first!
avatar_blob = File.open("avatar.jpg", "rb") do |file|
ActiveStorage::Blob.create_and_upload!(
io: file,
filename: "avatar.jpg",
service_name: "local",
content_type: "image/jpeg"
)
end
ActiveStorage::Attachment.create!(
record_type: "User",
record_id: user.id,
name: "avatar",
blob_id: avatar_blob.id
)
The content is read twice, once for the checksum and once for the upload, so the passed IO has to be rewindable, which is what a Rails app hands over.
Use .create! when the content is already in the service - when a Rails app uploaded it, say:
avatar_blob = ActiveStorage::Blob.create!(
key: "avatar",
filename: "avatar.jpg",
service_name: "rustfs",
byte_size: 4321,
content_type: "image/jpeg"
)
4. Serve The Rails Redirect Endpoint
A Marten app can serve the Rails route itself, so URLs issued by a Rails app keep resolving. Mount the handler on the same path Rails uses:
# config/routes.cr
require "marten_rails_bridge/active_storage/blobs/redirect_handler"
Marten.routes.draw do
path "/rails/active_storage/blobs/redirect/<signed_id:str>/<filename:path>",
MartenRailsBridge::ActiveStorage::Blobs::RedirectHandler,
name: "active_storage_blob"
end
The handler resolves the signed ID, then returns a 302 to a presigned service URL:
$ curl -I "http://localhost:8000/rails/active_storage/blobs/redirect/<signed_id>/avatar.jpg"
HTTP/1.1 302 Found
Location: http://127.0.0.1:9000/storage/avatar?X-Amz-Expires=300&...
Cache-Control: max-age=300, private
- The
filenameroute parameter only shapes the URL; the filename served to the client comes from the blob itself - A
?disposition=attachmentquery parameter forces a download - A tampered, expired or unknown signed ID returns a
404with an empty body and noCache-Control ActiveStorage.service_urls_expire_insets how long the presigned URL stays valid (default5.minutes, matching Rails)
# config/initializers/activestorage.cr
require "marten_rails_bridge/active_storage"
ActiveStorage.service_urls_expire_in = 2.hours
5. Serve The Rails Disk Endpoint
Blobs stored with the Disk service are served by the app itself. Mount the handler on the same path
Rails uses (Rails names this route rails_disk_service):
# config/routes.cr
require "marten_rails_bridge/active_storage/disk_handler"
Marten.routes.draw do
path "/rails/active_storage/disk/<encoded_key:str>/<filename:path>",
MartenRailsBridge::ActiveStorage::DiskHandler,
name: "active_storage_disk"
end
The encoded key is a signed payload carrying the service name, the blob key, the content type and the content disposition. The handler verifies it, then streams the file from disk:
$ curl -I "http://localhost:8000/rails/active_storage/disk/<encoded_key>/avatar.jpg"
HTTP/1.1 200 OK
Content-Type: image/jpeg
Content-Disposition: inline; filename="avatar.jpg"; filename*=UTF-8''avatar.jpg
Content-Length: 4321
Last-Modified: Sat, 17 Oct 2026 13:49:50 GMT
blob.urlreturns such a URL for a blob stored with aDiskService, so a Marten app can issue disk URLs itself. Rails reads them as long as both apps share the sameSECRET_KEY_BASE- The content type and the disposition come from the encoded key, not from the file extension
- A tampered, expired or unknown encoded key returns a
404with an empty body, and so does a missing file ActiveStorage.service_urls_expire_insets how long an issued key stays valid- A
Rangerequest is answered with a206and aContent-Rangeheader. A request asking for several ranges is answered with the whole file: Rails answers it with amultipart/byterangesbody, which is not supported here - An
If-Modified-Sinceheader matching the file returns a304
The service reads files on its own too:
service = ActiveStorage::Blob.services["local"].as(ActiveStorage::Service::DiskService)
service.exist?(blob.key) # => true
service.path_for(blob.key) # => "storage/gz/0z/gz0zdzhk..."
service.download(blob.key) # => the whole content
service.download(blob.key) { |bytes| ... } # => yields 5 MB chunks
service.download_chunk(blob.key, 0_i64..1023_i64) # => one byte range
path_for rejects a blank key, a key carrying a . or .. segment, a key carrying a null byte and
a key resolving outside of the root with ActiveStorage::InvalidKeyError. download and
download_chunk raise ActiveStorage::FileNotFoundError when nothing is stored for the key.
6. Serve The Rails Proxy Endpoint
The proxy endpoint streams the blob bytes through the app instead of redirecting. The response can then be cached by a CDN sitting in front of the app. Mount the handler on the same path Rails uses:
# config/routes.cr
require "marten_rails_bridge/active_storage/blobs/proxy_handler"
Marten.routes.draw do
path "/rails/active_storage/blobs/proxy/<signed_id:str>/<filename:path>",
MartenRailsBridge::ActiveStorage::Blobs::ProxyHandler,
name: "active_storage_blob_proxy"
end
blob.proxy_url returns such a URL, the one Rails names rails_storage_proxy_url. The handler
resolves the signed ID, reads the blob from its service and streams it back:
$ curl -I "http://localhost:8000/rails/active_storage/blobs/proxy/<signed_id>/avatar.jpg"
HTTP/1.1 200 OK
Content-Type: image/jpeg
Content-Disposition: inline; filename="avatar.jpg"; filename*=UTF-8''avatar.jpg
Content-Length: 3159
Accept-Ranges: bytes
Cache-Control: max-age=3155695200, public, immutable
Last-Modified: Sat, 01 Jan 2011 00:00:00 GMT
ETag: W/"..."
- The body is read from the service 5 MB at a time, so a large blob is not held in memory. Any
service reading bytes serves it: both
DiskServiceandS3Servicedo - The content type and the disposition follow the same serving rules as
blob.url, and a?disposition=attachmentquery parameter forces a download Cache-Control,Last-ModifiedandETagport the Railshttp_cache_foreverheaders- A tampered, expired or unknown signed ID returns a
404with an empty body and noCache-Control - A blob whose file is gone from the service returns a
404withCache-Control: no-cache - A
Rangeheader returns a206with aContent-Range, and noCache-Control. A range that cannot be served returns a416 Range Not Satisfiable
Two settings bound what one request may ask for, the ones Rails configures through
config.active_storage.*:
# config/initializers/activestorage.cr
require "marten_rails_bridge/active_storage"
ActiveStorage.streaming_max_ranges = 1 # ranges per request, `416` above it
ActiveStorage.streaming_chunk_max_size = 100 * 1024 * 1024 # bytes per range, `416` at or above it
It writes files too:
service = ActiveStorage::Blob.services["local"]
content = File.read("avatar.jpg").to_slice
service.upload(
"gz0zdzhk0yn6zjhxfzl6qt1ys5rj",
IO::Memory.new(content),
checksum: Digest::MD5.base64digest(content),
filename: ActiveStorage::Filename.wrap("avatar.jpg"),
content_type: "image/jpeg"
)
service.delete("gz0zdzhk0yn6zjhxfzl6qt1ys5rj")
7. Serve The Rails Representation Endpoint
A representation URL carries a signed blob ID and a signed variation key, and points at the variant a Rails app processed. Mount the handler on the path Rails uses:
# config/routes.cr
require "marten_rails_bridge/active_storage/representations/redirect_handler"
Marten.routes.draw do
path "/rails/active_storage/representations/redirect/<signed_blob_id:str>/<variation_key:str>/<filename:path>",
MartenRailsBridge::ActiveStorage::Representations::RedirectHandler,
name: "active_storage_representation"
end
Where Variants Live
config.active_storage.track_variants decides where Rails puts a variant:
| track_variants | Where the variant is | Storage key |
| ---------------- | -------------------------------------------------------------------- | --------------------------------------------------- |
| true | A blob of its own, linked by an active_storage_variant_records row | that blob's own key |
| false | A file under a key derived from the variation | variants/<blob key>/<SHA256 of the variation key> |
Rails' fallback is false, but load_defaults 6.1 turns it on, so most Rails 7 and 8 apps track
their variants.
This shard needs no configuration. It looks for a record first, and falls back to the derived key:
blob.variant(variation).key
# => "variantblobkey" # a tracked record exists
# => "variants/gz0zdz…/1349c67f…" # no record, so the derived key
Records match on variation_digest, which Rails computes as
SHA1.base64digest(Marshal.dump(transformations)). Ruby::Marshal reproduces that dump byte for
byte, asserted against output captured from real Ruby. A tracked variant needs the
active_storage_variant_records table from the Rails migration.
That digest is sensitive to how the transformations were written down: a spec of format: :jpg
carries a Symbol, while the same transformations decoded from a signed URL key carry the String
"jpg", and the two dump differently. Rails' controllers digest the decoded form, and its
preprocessed: true jobs digest the spec as written, so one variant can end up with two records.
The bridge queries both, decoded form first — the record Rails' controller would serve — then the
symbolized one, so an eagerly preprocessed variant serves before its URL has ever been decoded.
Only those two forms are queried, so a spec that mixes Symbol and String values is not found.
Set ActiveStorage.track_variants = false to skip the lookup query for an untracked Rails app.
URL Formats
Rails draws three representation routes, unchanged since 6.1. The handler reads the route parameters, not the path, so it can be mounted on any of them:
| Path | Rails route name |
| --------------------------------------------------------------------- | --------------------------------- |
| …/representations/redirect/:signed_blob_id/:variation_key/*filename | rails_blob_representation |
| …/representations/proxy/:signed_blob_id/:variation_key/*filename | rails_blob_representation_proxy |
| …/representations/:signed_blob_id/:variation_key/*filename | (unnamed, pre-6.1 alias) |
The third is the pre-6.1 path, still shipped as an alias, so an app upgraded from 6.0 may serve URLs in that shape. Mount the handler on it too if that applies:
Marten.routes.draw do
# The specific route first.
path "/rails/active_storage/representations/redirect/<signed_blob_id:str>/<variation_key:str>/<filename:path>",
MartenRailsBridge::ActiveStorage::Representations::RedirectHandler,
name: "active_storage_representation"
# The pre-6.1 alias last.
path "/rails/active_storage/representations/<signed_blob_id:str>/<variation_key:str>/<filename:path>",
MartenRailsBridge::ActiveStorage::Representations::RedirectHandler,
name: "active_storage_representation_legacy"
end
Declare the alias last. Its pattern also matches the redirect path, so declaring it first
makes redirect the signed_blob_id and every modern URL returns 404. Rails draws it last too.
The /rails/active_storage prefix is config.active_storage.routes_prefix. Use the Rails app's.
The handler resolves both signed values, finds where Rails stored the variant (see
Where Variants Live), and returns a 302 to a presigned service URL:
$ curl -I "http://localhost:8000/rails/active_storage/representations/redirect/<signed_blob_id>/<variation_key>/avatar.jpg"
HTTP/1.1 302 Found
Location: http://127.0.0.1:9000/storage/variants/avatar/1349c67f...?X-Amz-Expires=300&...
Cache-Control: max-age=300, private
- A variation nothing has stored is transformed, stored and then served, so this handler writes. See Processing A Variation
- It is served with the content type of its format, and the blob base name with that extension:
avatar.pngwithformat: jpgbecomesavatar.jpg ?disposition=attachmentforces a download- A tampered, expired or unknown signed value returns an empty
404, with noCache-Control - A blob whose content type is not in
ActiveStorage.variable_content_typesreturns a404, so an svg does too, although it is an image. No variant processor reads those, so Rails wrote no variant of them. Video and PDF previewers need ffmpeg or poppler and are not supported either - A variation whose
formathas no known MIME type returns a404
Processing A Variation
Rails processes a variation on the first request for it. Representations::BaseController asks for
blob.representation(variation_key).processed, and processed runs the transformations through
ActiveStorage.variant_processor, uploads the result and writes the row. Every later request is a
lookup. Rails' model DSL calls a named variation a variant.
This shard does the same, once a processor is assigned — see Installation for the two lines, because the default processes nothing. A request for a variation nothing has stored transforms the original, stores it, and serves it. So a representation URL works whether or not the Rails app ever processed it.
A GET that transforms is a GET that writes, which makes the authorization gate matter: an
unauthenticated request now costs CPU and storage, not just a lookup. See
Guard The Mounted Routes.
Resolution order, and it is not Rails' order:
- a tracked
active_storage_variant_recordsrow exists → serve it - otherwise the derived-key object exists → serve it
- otherwise transform, and store the layout
ActiveStorage.track_variantssays this app writes
Rails picks the layout from track_variants alone. The extra probe in step 2 costs one storage
existence call on a tracked miss, and buys serving both layouts without being told which one wrote
the data.
Transformations map onto libvips exactly as the image_processing gem maps them, so dimensions
match a Rails pass. Byte equality does not: it moves with the libvips version. A transformation the
processor does not implement raises ActiveStorage::UnsupportedImageProcessingMethod rather than
being skipped, because a variant stored without one of its transformations is wrong under a digest
saying it is right, and nothing recomputes it. resize_and_pad is not implemented.
Example available in crystal run examples/variant_processing.cr. It processes one variant on a
disk service with no database, because the untracked layout writes no rows. Pass
--transformations='{"format":"png","rotate":90}' to apply another variation, and --source=PATH
to use another image.
Letting Rails Do It Instead
Processing in the bridge is not required. Declaring every variation preprocessed: true keeps the
work in the Rails app, which is cheaper than transforming on request for a fixed set of sizes:
class User < ApplicationRecord
has_one_attached :avatar do |attachable|
attachable.variant :thumb, resize_to_fill: [125, 125], format: :jpg, preprocessed: true
end
end
preprocessed: true only covers uploads made after it is declared, so backfill the existing ones
once:
bin/rails runner 'User.find_each { |u| u.avatar.variant(:thumb).processed if u.avatar.attached? }'
Measured on the development database of a Rails 8 app, 2026-10-20, before this shard could process:
| Variation | preprocessed: true | Rows before the request |
| ------------------------ | -------------------- | ----------------------- |
| thumb | yes | written on upload |
| landing, big_landing | no | none |
The preprocessed thumb then gained a second row the first time Rails' own controller served it:
the processing pass and the controller write down the same transformations differently. Which
digests the lookup matches is in Where Variants Live.
8. Guard The Mounted Routes
# config/routes.cr
require "marten_rails_bridge/active_storage/blobs/redirect_handler"
class BlobRedirectHandler < MartenRailsBridge::ActiveStorage::Blobs::RedirectHandler
# Repeat the verbs: a subclass gets its own `@@http_method_names` copy, initialized to the full
# `Marten::Handlers::Base::HTTP_METHOD_NAMES` list and not to the parent's `:get, :head`.
http_method_names :get, :head
before_dispatch :authenticate
private def authenticate : Marten::HTTP::Response?
head(::HTTP::Status::UNAUTHORIZED) if request.session[:user_id]?.nil?
end
end
Marten.routes.draw do
path "/rails/active_storage/blobs/redirect/<signed_id:str>/<filename:path>",
BlobRedirectHandler,
name: "active_storage_blob"
end
Purging
Remove a blob together with everything derived from it — its variant records, the image blob of each, and the stored objects of all of them:
blob.purge # => true when removed, false when still attached or never saved
purge refuses a blob something is still attached to (it returns false and
removes nothing), so detach first or purge through the attachment:
attachment.purge # deletes the attachment row, then purges the blob
ActiveStorage::Attachment.purge(record_type, record_id, name) # => count removed
ActiveStorage::Attachment.purge(attachment_id) # => true/false
File deletion runs synchronously against the configured service, for both the
disk and the S3 service, including the variants/<blob key>/ prefix for image
blobs. purge_later is available as an alias of purge (there is no background
job queue in this bridge).
Service URL Shape
The Location a redirect handler sends is a presigned storage URL of three independent parts:
http://127.0.0.1:9000 / storage / variants/avatar/1349c67f... ?X-Amz-Expires=300&...
└─ endpoint ──────────┘ └bucket┘ └─ object key ─────────────┘ └─ signature ──────┘
The endpoint and the bucket come from the S3Service configuration. force_path_style decides
where the bucket goes:
| Configuration | Resulting URL |
| ------------------------- | ------------------------------------------- |
| force_path_style: true | http://127.0.0.1:9000/storage/1349c67f... |
| force_path_style: false | http://storage.127.0.0.1:9000/1349c67f... |
Virtual-host style gives the short form, reading as https://storage.example.com/1349c67f... with a
real domain. The bucket cannot be dropped: an empty bucket: yields a double slash in path style
and a broken hostname in virtual-host style. To serve from the root of a host, point endpoint: at
a CDN or reverse proxy whose root maps to the bucket.
The object key is not a formatting choice. It is where the file is, and the signature covers the
path, so shortening variants/<blob key>/<digest> points at a different object and the storage
returns 404. Whatever wrote the variant fixes the layout, normally Rails, which hardcodes both
layouts in Where Variants Live.
The signature is there because these services are private. Rails serves a public service with an
unsigned URL through Service#public_url, a stub returning "" in both S3Service and
DiskService. Public services are not supported yet; that is the route to clean URLs, not reshaping
keys.
URL Helpers
blob.urlgenerates a direct presigned URL from configured object storageblob.redirect_urlreturns a Rails redirect URL (/rails/active_storage/blobs/redirect/...)blob.proxy_urlreturns a Rails proxy URL (/rails/active_storage/blobs/proxy/...)blob.representation_url("thumb")returns a Rails representation redirect URL- Built-in variation names:
thumb,medium,landing,big_landing ActiveStorage::Variation.decode(variation_key, verifier)returns the transformations a signed variation key carriesActiveStorage::Variant.new(blob, variation).keyreturns the storage key of a variant, and#urla presigned URL for it
Signed IDs
ActiveStorage::Blob.find_signed(signed_id)returns the blob, ornilwhen the signed ID is tampered with, carries another purpose, has expired, or no longer matches a recordActiveStorage::Blob.find_signed!(signed_id)raisesActiveSupport::MessageVerifier::InvalidSignaturefor an invalid signed ID andMarten::DB::Errors::RecordNotFoundwhen the signed ID is valid but the blob is gone
Behavior Notes
service_namemust exist inActiveStorage::Blob.services(ArgumentErrorotherwise)- Unknown variation names raise
ArgumentError content_typecan be nil, and defaults toapplication/binaryfor direct URL generation- Signed IDs depend on
ActiveSupport::KeyGenerator.instance; configure it with the same secret as Rails (SECRET_KEY_BASE) for interoperability blob.urlfollows the Rails serving rules: content types that a browser would execute (text/html,image/svg+xml, ...) are served asapplication/octet-stream, and anything not inActiveStorage.content_types_allowed_inlineis forced toContent-Disposition: attachment. Both lists are configurable throughActiveStorage.content_types_to_serve_as_binaryandActiveStorage.content_types_allowed_inline- Served filenames are sanitized (
foo/bar.jpgbecomesfoo-bar.jpg) and emitted with both thefilenameand the RFC 5987filename*parameters, as Rails does blob.downloadreturns the whole body,blob.download { |chunk| ... }yields it 5 MB at a time, andblob.download_chunk(0_i64..1023_i64)returns one byte range- A file missing from the service raises
ActiveStorage::FileNotFoundError variant.processedtransforms and stores the variant when nothing has stored it, as Rails does (see Processing A Variation). A variation without aformatfalls back topng, as Rails does, instead of being resolved from the blobblob.variant(variation)returns anActiveStorage::VariantWithRecordwhen a record exists or when this app tracks variants, and anActiveStorage::Variantwhen the derived-key object is the one that is stored; both answerkey,filename,content_type,urlandprocessedActiveStorage::Variation#digestfingerprints the transformations for the variant record lookup and is not the same thing as#key, which signs them for the URL
For a complete runnable example, see examples/demo.
ActionText::RichText
This shard maps Rails ActionText rich text records to a Marten model:
ActionText::RichText->action_text_rich_texts
Minimal Usage
require "marten_rails_bridge/action_text/rich_text"
class Article < Marten::Model
db_table :articles
field :id, :big_int, primary_key: true, auto: true
field :title, :string, max_size: 255
def rich_text_body
ActionText::RichText.get_or_initialize_by(
record_type: "Article",
record_id: id,
name: "body"
)
end
def set_rich_text_body(value : String)
text = rich_text_body
text.body = value
text.save!
end
end
Render stored content:
article = Article.first!
html = article.rich_text_body.to_html
text = article.rich_text_body.to_plain_text
Example available in crystal run examples/action_text_rich_text.cr.
Persistence Model
- Rich text HTML is stored in
action_text_rich_texts.body - One rich text field is identified by
(record_type, record_id, name) - Attachments for rich text embeds are resolved through:
active_storage_attachmentswithrecord_type = "ActionText::RichText"andname = "embeds"active_storage_blobsfor blob metadata and redirect URL generation
Supported Behavior
- Rich text retrieval and persistence through
ActionText::RichText - Conversion of
<action-text-attachment>image nodes into<img src="..."> - SGID-based blob resolution for embedded ActiveStorage images
- External image attachment rendering when
content-type="image"andurlare provided
Known Gaps vs Rails ActionText
- No direct
has_rich_textintegration helper on Marten models yet - No built-in sanitization pipeline (content is not sanitized before rendering)
- No Trix/editor integration APIs
- No rich text fragment/canonicalization layer equivalent to Rails
ActionText::Content - Limited embed handling: currently focused on image-style attachments
- No full ActiveStorage attachable rendering variants (
figure, captions, galleries) parity - No ActiveStorage direct-upload integration (
DirectUploadsControllerworkflow) - No ActiveStorage analyzers/previewers/transformers integration for ActionText embeds
- No automatic dependency on ActiveStorage presence checks
- No ActionMailbox / ActionText attachment extraction workflows
Future Improvements
- Add
ActiveSupport::MessageVerifierverification helpers (verify,verified) for signed payload validation - Add first-class
GlobalIDand locator registry compatibility APIs - Add model-instance helpers for
SignedGlobalID.createparity with upstream globalid - Implement encryption message public tags support in
ActiveRecord::Encryption::Encryptor - Implement compression and decompression support in
ActiveRecord::Encryption::Encryptor - Add optional debug trace logging path in
ActiveRecord::Encryption::Cipher - Add a custom Marten field type to automate encrypted attribute read/write flows
- Add
Attachment.attachand#purgehelpers, and a multipart upload handler - Add configurable ActiveStorage service loading from environment or config file
- Add support for UUID primary keys and non-standard table names in ActiveStorage models
- Support
Marshalpayloads other than aString, for encrypted files written by something other thanActiveSupport::EncryptedFile - Support the JSON and MessagePack serializers
config.active_support.message_serializercan select forActiveSupport::MessageEncryptor
Installation
-
Add the dependency to your
shard.yml:dependencies: marten_rails_bridge: codeberg: miry/marten-rails-bridge branch: master -
Run
shards install -
Only to transform variants, install libvips and assign the processor:
brew install vips # macOS apt-get install libvips-dev # Debianrequire "marten_rails_bridge/active_storage/variant_processor/vips_processor" ActiveStorage.variant_processor = ActiveStorage::VariantProcessor::VipsProcessor.newNothing else needs libvips. Crystal links at compile time, so requiring the processor from the configuration would make the library a build dependency of every consumer, including the ones that only generate URLs — the default processor therefore runs nothing. The binding links with a plain
-lvips, so the runtimelibvips42package alone does not satisfy the linker.
Development
shards install
rake fmt test
rake test:all runs every test, so start the databases and the object storage first:
podman compose up -d postgres mysql rustfs
rake test:db:migrate test:all
Run DB-backed tests against a specific adapter:
podman compose up -d postgres mysql rustfs
# Default local SQLite in ./tmp when DATABASE_URL is not set:
rake test:db:migrate test:all
DATABASE_URL="sqlite3://$(pwd)/tmp/marten_rails_bridge_test.sqlite3" rake test:db:migrate test:all
DATABASE_URL="postgres://bridge:bridge@127.0.0.1:5432/bridge_test" rake test:db:migrate test:all
DATABASE_URL="mysql://bridge:bridge@127.0.0.1:3306/bridge_test" rake test:db:migrate test:all
podman compose down
Please note that the folder structure differs from typical Crystal projects; test files are located alongside source files.
The project uses minitest.cr as the testing framework.
Credits & inspirations
This work draws inspiration from various libraries and documentation resources to enhance functionality and provide seamless integration:
- https://codeberg.org/miry/zbar.cr
- https://github.com/martenframework/marten-auth
- https://github.com/ellmetha/marten-raven-middleware
Contributing
- Fork it (https://github.com/miry/marten-rails-bridge/fork)
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Push to the branch (
git push origin my-new-feature) - Create a new Pull Request
Contributors
- miry - creator and maintainer