On Nov 13, 2007, at 7:24 AM, Trans wrote:

> What's the best way to avoid the classic method_added/define_method
> infinite loop?
>
>   class X
>     def self.method_added(name)
>       p name
>       define_method(name)
>          # do something else
>       end
>     end
>
>      def foo; end
>   end
>
> This will, of course, print "foo" forever.
>
> As an aside, anyone else think method_added should also receive a
> block of the method definition? E.g. this would be a "push" (less the
> infinite loop issue):
>
>     def self.method_added(name, &block)
>       define_method(name, &block)
>     end
>
> Thanks!
> T.
>
>



cfp:~ > cat a.rb
class X
   class << self
     def ignoring_added_methods
       ignoring_added_methods = @ignoring_added_methods
       @ignoring_added_methods = true
       yield
     ensure
       @ignoring_added_methods = ignoring_added_methods
     end

     def ignoring_added_methods?
       defined? @ignoring_added_methods and @ignoring_added_methods
     end

     def method_added name
       return if ignoring_added_methods?
       ignoring_added_methods do
         p name
         define_method(:bar){}
       end
     end
   end

    def foo
    end
end



cfp:~ > ruby a.rb
:foo


a @ http://codeforpeople.com/
--
it is not enough to be compassionate.  you must act.
h.h. the 14th dalai lama