Stand With Ukraine

Marten Rails Bridge

Stand With Ukraine status-badge

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:

Out of scope:

Features

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:

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:

Intentional deviations from upstream globalid:

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:

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
# 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

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/"..."

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

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:

  1. a tracked active_storage_variant_records row exists → serve it
  2. otherwise the derived-key object exists → serve it
  3. otherwise transform, and store the layout ActiveStorage.track_variants says 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

Signed IDs

Behavior Notes

For a complete runnable example, see examples/demo.

ActionText::RichText

This shard maps Rails ActionText rich text records to a Marten model:

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

Supported Behavior

Known Gaps vs Rails ActionText

Future Improvements

Installation

  1. Add the dependency to your shard.yml:

    dependencies:
      marten_rails_bridge:
        codeberg: miry/marten-rails-bridge
        branch: master
  2. Run shards install

  3. Only to transform variants, install libvips and assign the processor:

    brew install vips           # macOS
    apt-get install libvips-dev # Debian
    require "marten_rails_bridge/active_storage/variant_processor/vips_processor"
    
    ActiveStorage.variant_processor = ActiveStorage::VariantProcessor::VipsProcessor.new

    Nothing 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 runtime libvips42 package 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:

Contributing

  1. Fork it (https://github.com/miry/marten-rails-bridge/fork)
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

Contributors