今天没事看blog的时候,看到一个小子实现了这个,不过他的程序写的那叫一个丑陋,实在是看不下去,就自己写了个.
原理很简单,那就是首先将要检测的方法重命名掉,然后动态定义一个相同的,这时他就会调用我们定义的这个方法,这时我们就可以检测参数的类型的,检测如果成功,在最后调用我们刚才重命名过的那个方法:
原理很简单,那就是首先将要检测的方法重命名掉,然后动态定义一个相同的,这时他就会调用我们定义的这个方法,这时我们就可以检测参数的类型的,检测如果成功,在最后调用我们刚才重命名过的那个方法:
class Object
class << self
def check_type method_name,*arg_type
raise ArgumentError, "method_name is missing" unless new.respond_to?(method_name)
arg_count=new.method(method_name).arity
alias_method :"old_#{method_name}",method_name
define_method(method_name) do |*args|
raise ArgumentError,"wrong number of arguments(#{args.length} of #{arg_count})" if arg_count>=0 and arg_count!=args.length
message=""
args.each_with_index do |item,index|
break if arg_type[index]==nil
message << "argument type is wrong(#{item.class} of #{arg_type[index]}" if item.class!=arg_type[index]
end
raise ArgumentError,message unless message==""
send(:"old_#{method_name}",*args)
end
end
end
end
class Test
def bar(x,y,z)
p [x,y,z]
end
check_type :bar,String
end
Test.new.bar(1,2,5)
Test.new.bar("a",1,2)