Skip to content
This repository
branch: experimental

This branch is 2 commits ahead and 43 commits behind master

Fetching latest commit…


Cannot retrieve the latest commit at this time

Octocat-spinner-32 lib
Octocat-spinner-32 spec
Octocat-spinner-32 .gitignore adding gitignore June 07, 2012
Octocat-spinner-32 LICENSE
Octocat-spinner-32 TODO.markdown
Octocat-spinner-32 VERSION
Octocat-spinner-32 contracts.gemspec


Contracts let you clearly – even beautifully – express how your code behaves, and free you from writing tons of boilerplate, defensive code.

You can think of contracts as assert on steroids.


gem install contracts

Running Tests

rspec spec/*.rb

Hello World

A contract is one line of code that you write above a method definition. It validates the arguments to the method, and validates the return value of the method.

Here is a simple contract:

  Contract Num => Num
  def double(x)

This says that double expects a number and returns a number. Here's the full code:

require 'contracts'
include Contracts

Contract Num => Num
def double(x)
  x * 2

puts double("oops")

Save this in a file and run it. Notice we are calling double with "oops", which is not a number. The contract fails with a detailed error message:

./contracts.rb:34:in `failure_callback': Contract violation: (RuntimeError)
    Expected: Contracts::Num,
    Actual: "oops"
    Value guarded in: Object::double
    With Contract: Contracts::Num, Contracts::Num
    At: main.rb:6 
    ...stack trace...

Instead of throwing an exception, you could log it, print a clean error message for your user...whatever you want. contracts.ruby is here to help you handle bugs better, not to get in your way.


Check out this awesome tutorial.


Contracts don't work on top level functions. Any function with a contract should be in a class. In our example we just stuck the double function in the Object class.

Q. Is this compatible with Ruby 1.9?

A. Yes.

If you're using the library, please let me know what project you're using it on :)


Inspired by

Copyright 2012 Aditya Bhargava.

BSD Licensed.

Something went wrong with that request. Please try again.