-
-
Save cookrn/8367449 to your computer and use it in GitHub Desktop.
What would a library for Ruby look like that implemented some sort of runtime 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
class Printer | |
attr_reader :printer | |
deftyped :initialize , :printer => [ Proc ] do | |
@printer = printer | |
end | |
deftyped :print , :string => { :splat => true , :type => String } do | |
printer.call string.join( ' ' ) | |
end | |
end |
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 Object | |
def deftyped( method_name , method_arg_defns , &block ) | |
TypedMethod.register \ | |
self, | |
method_name, | |
method_arg_defns, | |
&block | |
define_method method_name do | *args , &block | | |
TypedMethod.call \ | |
self, | |
method_name, | |
*args, | |
binding, | |
&block | |
end | |
end | |
end | |
class TypedMethod | |
def self.call( object , method_name , *args , binding , &block ) | |
id = id_for object , method_name | |
typed_method = Thread.current[ id ] | |
raise NoMethodError unless typed_method | |
typed_method.call \ | |
*args, | |
binding, | |
&block | |
end | |
def self.id_for( object , method_name ) | |
real_object = | |
if object.ancestors.include? Class | |
object | |
else | |
object.class | |
end | |
:"#{ real_object.name }_#{ method_name }" | |
end | |
def self.register( object , method_name , method_arg_defns , &block ) | |
id = id_for object , method_name | |
Thread.current[ id ] = | |
new \ | |
object, | |
method_name, | |
method_arg_defns, | |
&block | |
end | |
def initialize( *args , &block ) | |
# do stuff | |
end | |
def call( *args , &block ) | |
# do stuff | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment