From: Erik Veenstra Date: 2006-02-08T07:33:21+09:00 Subject: Re: Meta-Meta-Programming I forgot to show you the implementation of this "typed". Well, here it is... gegroet, Erik V. - http://www.erikveen.dds.nl/ ---------------------------------------------------------------- # IMPLEMENTATION class Module def typed(method_name, *types) wrap_method(method_name) do |org_method, args, block| args.each_with_index do |args, n| [types[n]].flatten.each do |typ| if typ.kind_of?(Module) unless arg.kind_of?(typ) raise ArgumentError, "Wrong argument type (#{arg.class} instead of #{typ}, argument #{n+1})." end elsif typ.kind_of?(Symbol) unless arg.respond_to?(typ) raise ArgumentError, "#{arg} doesn't respond to :#{typ} (argument #{n+1})." end else raise ArgumentError, "Wrong type in types (#{typ}, argument #{n+1})" end end end org_method.call(*args, &block) end end end ---------------------------------------------------------------- # TEST SCRIPT class Foo def bar(x, y, z) # x should be Numeric # y should be a String # z should respond to :gsub and :to_s :good end typed :bar, Numeric, String, [:gsub, :to_s] end def test(*args) begin puts "#{args.inspect} : OK : #{Foo.new.bar(*args).inspect}" rescue Exception => e puts "#{args.inspect} : NOK : #{e.message}" end end puts puts File.open(__FILE__){|f| f.readlines}.select{|x| x =~ /^\s*typed\b/}.join("\n") puts test(7) test(7, 8, 9) test(7, 8, "9") test(7, "8", 9) test(7, "8", "9") ----------------------------------------------------------------