Skip to content

Instantly share code, notes, and snippets.

@baweaver
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save baweaver/eebce3daceabd4055a4e to your computer and use it in GitHub Desktop.
Save baweaver/eebce3daceabd4055a4e to your computer and use it in GitHub Desktop.
Ala banisterfiend's cleverness: https://gist.github.com/banister/acec9b4688cbb7575106 - I made it do something else interesting
def static_typed(types={})
type, method_name = types.first
old_method = instance_method(method_name)
define_method(method_name) do |*args, &block|
old_method.bind(self).call(*args, &block).tap { |return_value|
raise TypeError, "Return value is not of type #{type}!" unless type === return_value
}
end
end
# ---------------------------------
[8] pry(#<Foo>)> class Foo
[8] pry(#<Foo>)* static_typed Integer => def foo(i) i end
[8] pry(#<Foo>)* end
=> :foo
[9] pry(#<Foo>)> Foo.new.foo(1)
=> 1
[10] pry(#<Foo>)> Foo.new.foo('s')
TypeError: Return value is not of type Integer!
from (pry):157:in `block (2 levels) in static_typed`
# Though you can be even more sneaky:
[14] pry(#<Foo>)> class Bar
[14] pry(#<Foo>)* static_typed /[A-Z]+/ => def baz(s) s end
[14] pry(#<Foo>)* end
=> :baz
[15] pry(#<Foo>)> Bar.new.baz('s')
TypeError: Return value is not of type (?-mix:[A-Z]+)!
from (pry):174:in `block (2 levels) in static_typed`
[16] pry(#<Foo>)> Bar.new.baz('S')
=> "S"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment