From: Robert Dober Date: 2007-05-31T05:31:24+09:00 Subject: Re: #respond_to? not working for dynamically generated metho On 5/30/07, James Edward Gray II wrote: > On May 30, 2007, at 9:57 AM, Maurice Gladwell wrote: > > > It would be interesting to see an implementation of James Edward > > Gray's > > suggestion above. ("You use an Extract Method refactoring to pull out > > the matching logic into a separate private method and use that in > > both implementations.") > > #!/usr/bin/env ruby -wKU > > class Test > def initialize(*fields) > @fields = fields.map { |f| f.to_s } > end > > def find(*args) > "Performing query with args:\n#{args.inspect}" > end > > def method_missing(meth, *args, &block) > if find_args = dynamic_finder?(meth) > find( find_args.first, > :conditions => find_args[1..-1].zip(args). > map { |n, v| "#{n} = '# > {v}'"}. > join(" AND ") ) > else > super > end > end > > def respond_to?(*args) > super || dynamic_finder?(args.first) > end > > private > > def dynamic_finder?(method_call) > if method_call.to_s =~ /\Afind(_all)?_by_(\w+)\Z/ > args = [$1 ? :all : :first] > args += $2.split("_and_") > args if args[1..-1].all? { |f| @fields.include? f } > end > end > end > > if __FILE__ == $PROGRAM_NAME > model = Test.new(:name, :age, :height, :weight) > > p !!model.respond_to?(:find_by_name_and_height) > p !!model.respond_to?(:find_all_by_age) > p !!model.respond_to?(:find_all_by_race) > > puts > > puts model.find_by_name_and_height("James", "61 in.") > puts model.find_all_by_name_and_height > end > > James Edward Gray II > > > This is very interesting, I just imagine that dynamic_finder does not give consistent results depending on events outside the Ruby program(*). Are you still happy with the semantics, instead of respond_to? giving false negatives it gives false positives now. A second issue was brought up by David,( I have no idea why he put a smiley ;) You have created a dependency between method_missing and respond_to? I really feel bad about this. Robert (*) or maybe by threading -- You see things; and you say Why? But I dream things that never were; and I say Why not? -- George Bernard Shaw