contracts-rb

Make Ruby promises executable.

contracts-rb adds lightweight behavioral contracts to Ruby methods and objects—without turning Ruby into a static type system.

Ruby 3.1+ Runtime contracts for methods, services, and stateful domain objects.

Behavior you can state, inspect, and enforce.

Method contracts

Validate parameters, preconditions, return values, and postconditions with idiomatic Ruby blocks.

State safety

Capture immutable before-state snapshots, preserve invariants, and declare permitted changes.

Production control

Sample enforcement, redact sensitive values, configure failure modes, and inspect contracts through the CLI.

Five-minute start

gem "contracts-rb"

class Account
  include Contracts
  attr_reader :balance

  invariant { balance >= 0 }

  contract :withdraw do
    params amount: Numeric
    requires { |amount:| amount.positive? }
    observe :balance
    changes :balance
    returns Numeric
  end
end

Read the README for snapshots, exceptions, inheritance, RSpec, Rails, and CLI usage.