Created
May 9, 2012 00:15
-
-
Save Veejay/2640633 to your computer and use it in GitHub Desktop.
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
class Array | |
def extract_options! | |
last.is_a?(::Hash) ? pop : {} | |
end | |
end | |
def assert_types *args, &block | |
options = args.extract_options! | |
# Check that the block has the proper arity | |
raise ArgumentError, "Expected #{options[:passed].count} arguments, got #{args.count}" unless options[:passed].count == args.count | |
# Check that the parameters have the proper "type" | |
raise ArgumentError, "Method has signature (#{options[:passed].join(", ")}) => #{options[:returned]}" unless args.zip(options[:passed]).all? { |param, klass| param.is_a? klass } | |
out = block.call args | |
# Check that the returned value conforms to the expected signature of the method | |
raise TypeError, "Method has signature (#{options[:passed].join(", ")}) => #{options[:returned]}" unless out.is_a? options[:returned] | |
out | |
end | |
def multiply x, y | |
assert_types(x, y, {:passed => [Fixnum, Fixnum], :returned => Fixnum}) do |a,b| | |
(a*b).to_s | |
end | |
end | |
puts multiply "a", 5 | |
# with_types.rb:14:in `assert_types': Method has signature (Fixnum, Fixnum) => Fixnum (ArgumentError) | |
# from with_types.rb:23:in `multiply' | |
# from with_types.rb:28 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment