Last active
August 29, 2015 14:04
-
-
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
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
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