Skip to content

Instantly share code, notes, and snippets.

@cookrn

cookrn/a.rb

Last active Jan 2, 2016
Embed
What would you like to do?
What would a library for Ruby look like that implemented some sort of runtime type checking?
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
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