From: James Edward Gray II Date: 2007-05-31T00:28:33+09:00 Subject: Re: #respond_to? not working for dynamically generated metho 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