検出方法のパラメータタイプのウィジェット

1352 ワード

詳細
今日blogを见る暇がない时、1人の小さい子がこれを実现したことを见て、しかし彼のプログラムの书くあれは丑くて、本当に见ることができなくて、自分で书きました.
原理は簡単で、それはまず検出する方法の名前を変更して、それから動的に同じ方法を定義して、この時彼は私たちが定義したこの方法を呼び出して、この時私たちはパラメータのタイプを検出することができて、検出が成功すれば、最後に私たちがさっき再命名した方法を呼び出します:

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)