Antidote
Antidote is a small, highly experimental library that performs runtime type assertions in Ruby in the same vein as Rubype, contracts.ruby, sig, and so on. This repository should mainly be considered a proof of concept.
It relies heavily on metaprogramming, and it is unsafe for method calls with side-effects. Nonetheless, it works.
Antidote exposes two methods: annotate
, and annotate_class_method
which can
be used a such:
require_relative 'lib/antidote'
class Adder
include Antidote
annotate Fixnum, Fixnum, Fixnum do
def add(x, y)
x y
end
end
end
adder = Adder.new.add(1, 2)
Here, annotate Fixnum, Fixnum, Fixnum
means that we expect two Fixnum
as
input, and we should return a Fixnum
as result.
This program returns 3 as expected since we comply with the type signature, but
if we change x
to be a String
, we receive the following error message:
Variable `x` in method `add` expected a String, but received a Fixnum
(Antidote::VariableTypeError)
If we change the return type, we'll see a similar message:
Expected `add` to return a String, but it returned a Fixnum instead
(Antidote::ReturnTypeError)
You can obviously handle both Antidote::VariableTypeError
and
Antidote::ReturnTypeError
in your code if needed.
Please, visit example.rb
for a full example.
Requirements
- Ruby 2.2.0 or newer.
Installation
Add this line to your Gemfile:
gem 'antidote-types'
And then run:
bundle
Or simply install it yourself:
gem install antidote-types
Contribute
- Fork it.
- Create your feature branch (
git checkout -b my-new-feature
). - Commit your changes (
git commit -am 'Add some new feature.'
). - Push to the branch (
git push origin my-new-feature
). - Create a new pull request.
License
See LICENSE. Copyright (c) 2014 Mathias Jean Johansen <[email protected]>