From: Eric Mahurin Date: 2006-09-22T02:19:12+09:00 Subject: Re: Ducktator - A Duck Type Validator ------=_Part_6875_9928646.1158859149901 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline On 9/21/06, ara.t.howard@noaa.gov wrote: > > On Fri, 22 Sep 2006, Austin Ziegler wrote: > > > On 9/21/06, Gregory Seidman wrote: > >> Actually, it is the developer's responsibility to override respond_to? > when > >> overriding method_missing. To do one and not the other is just sloppy. > > > > Maybe. I did point out that in my early days of programming Ruby, I > > would implement one without the other. But simply doing a #respond_to? > > check doesn't help you with arity checking, which matters as much as > > the presence of the method itself. > > > > -austin > > that's pretty interesting austin - i haven't considered that before. i'm > already in the habit of checking arity on blocks and calling them with the > 'correct' number of paramters - i wonder if a simple design pattern might > help > with that situation, for example: > > harp:~ > cat a.rb > # > # an open-struct class, with a demo impl of method_missing/respond_to > pair > # > class OpenStruct > def initialize h = {} > (@h = {}).update h > end > > def method_missing m, *a, &b > key = m.to_s > w = key.sub! %r/=$/, '' > if w > val = a.shift || b.call > @h[key] = val > else > @h[key] > end > end > > def respond_to? m > if super > method m > else > key = m.to_s > w = key.sub! %r/=$/, '' > w ? lambda{|k,v|} : lambda{|k|} > end > end > end > > os = OpenStruct.new 'key' => 'val', 'a' => 'b' > os.x = 'y' > > if how = os.respond_to?('x') > puts "'x' artiy : #{ how.arity }" > end > > if how = os.respond_to?('x=') > puts "'x=' artiy : #{ how.arity }" > end > > if how = os.respond_to?('to_s') > puts "'to_s' artiy : #{ how.arity }" > end > > if how = os.respond_to?('send') > puts "'send' artiy : #{ how.arity }" > end > > > harp:~ > ruby a.rb > 'x' artiy : 1 > 'x=' artiy : 2 > 'to_s' artiy : 0 > 'send' artiy : -1 > > > so, rather than returning a simple bool from 'respond_to?' we return an > object > describing __how__ it responds - either a method object or a lambda, > either of > which can be used to determin arity. > > just a thought... > > cheers. > > -a > -- > in order to be effective truth must penetrate like an arrow - and that is > likely to hurt. -- wei wu wei > > No reason to go change the API... If you want to get the arity of a method, you simply use #method to get the method object and use arity on that. If you overrode #method along with #method_missing, you could still implement this same behaviour. You might make #method return a Proc instead of a Method for those cases, but it shouldn't make much difference. So, these should really be overridden together: method_missing respond_to? method You could put most of your logic in #method and have #method_missing and #respond_to? use it. ------=_Part_6875_9928646.1158859149901--