The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Hatching New Methods in Mid-air

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Red Handed

Posts: 1158
Nickname: redhanded
Registered: Dec, 2004

Red Handed is a Ruby-focused group blog.
Hatching New Methods in Mid-air Posted: May 30, 2005 5:41 PM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Red Handed.
Original Post: Hatching New Methods in Mid-air
Feed Title: RedHanded
Feed URL: http://redhanded.hobix.com/index.xml
Feed Description: sneaking Ruby through the system
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Red Handed
Latest Posts From RedHanded

Advertisement

Ken Miller sent in a very interesting class, which creates new methods as they are needed. And, also, the respond_to? method is hacked to respond positively in these cases. I could see this kind of thing going into Rails so you can Student.find_classes or Student.find_grades. That sort of thing.

 class MethodMagic

   alias_method :old_respond_to?, :respond_to?

   def respond_to? (method, include_private=false)
     old_respond_to?(method.to_sym, include_private) || 
     create_dynamic_method(method)
   end

   alias_method :old_method_missing, :method_missing

   def method_missing(method, *args)
     if create_dynamic_method(method)
       send(method.to_sym, *args)
     else
       old_method_missing(method)
     end
   end

   # If the method name conforms to our rigorous specifications, 
   # create a new body on the fly and define the sucker
   def create_dynamic_method(method)
     if method.to_s.match /^find_by_/
       self.class.send(:define_method, method.to_sym) { |*args|
         puts "Called #{method}(#{args.join ", "})" 
       } 
       true
     else
       false
     end
   end

   # just here as an example of a normal method
   def find; end

end

mm = MethodMagic.new

p mm.respond_to?(:find)            # => true
p mm.respond_to?(:find_by_letters) # => true
mm.find_by_letters("a", "b", "c")  # prints 'Called find_by_letters(a, b, c)'
mm.find_by_numbers(1, 2, 3)        # prints 'Called find_by_numbers(1, 2, 3)'

p mm.respond_to?(:poopy)           # => false
mm.poopy                           # raises NoMethodError

What about you? Do you have any metaprogramming tricks for us? If nothing else, read Ruby/X11 source and get back to me.

Read: Hatching New Methods in Mid-air

Topic: Backpack in WSJ Previous Topic   Next Topic Topic: Windows, Unicode and C programming tips

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use