Created
October 11, 2013 01:04
-
-
Save fabioyamate/6928121 to your computer and use it in GitHub Desktop.
type checking
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# gem install mar | |
# this only checks at runtime, so it doesn't verify the type at compilation | |
require 'mar' | |
def type_check(type, value) | |
value.is_a?(type) or raise "#{value} is not type of #{type}" | |
end | |
def type_signature(*types) | |
->(original, *args, &blk) do | |
types[0..-2].zip(args).each do |(type, arg)| | |
type_check(type, arg) | |
end | |
result = original.call(1, 2, &blk) | |
type_check(types[-1], result) | |
result | |
end | |
end | |
class Foo | |
_ type_signature(Integer, Integer, Integer) | |
def foo(one_arg, two_arg) | |
one_arg + two_arg | |
end | |
end | |
puts Foo.new.foo(1, 2) | |
# => 3 | |
puts Foo.new.foo(1, 'a') | |
# raises: a is not type of Integer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment