avy
avy

Reputation: 572

instance_eval, define_method and method_missing

guys. I create a class:

class A
  def initialize &b
    instance_eval &b
  end

  def method_missing method_id, *args
    self.define_method(method_id) { puts args.first }
  end
end

b = A.new { new_method "oops" }

But is does not work

SystemStackError: stack level too deep

Why?

Upvotes: 2

Views: 1525

Answers (1)

mb14
mb14

Reputation: 22636

define_method is not defined for an instance of A, so when you call self.define_method that cal method_missing again, an again => stack overflow.

You need to do something like that instead

class A
     def initialize &b
       instance_eval &b
     end

     def method_missing(method_id, *args)
       self.class.instance_eval do
         define_method(method_id) { debugger; puts args.first }
       end
     end
   end

Upvotes: 6

Related Questions