2

I tried to implement a class allowing its subclasses to save method blocks for get them executed later. It work's, but it seems I took the wrong way. Have a look at this:

class SuperKlass  
  def self.exec_later(&block)
    @@block_for_later = block
  end

  def exec_now
    return unless @@block_for_later
    @@block_for_later.call
  end
end

class ChildKlass < SuperKlass
  exec_later do
    child_method
  end

  def child_method
    puts "Child method called"
  end
end

test_klass = ChildKlass.new
test_klass.exec_now

If I try to execute this piece of code, the call to child_method in the block results in a method-missing error. Does somebody know what I'm doing wrong, and what's the right way to add functionality like this?

1 Answer 1

4

The block exec_later is running in the context of ChildKlass, not the instance test_klass. As child_method is an instance method, it isn't found on ChildKlass.

UPDATE: I found a solution:

  def exec_now
    return unless @@block_for_later
    instance_eval &@@block_for_later
  end
Sign up to request clarification or add additional context in comments.

3 Comments

Great, this works. Allthough I knew about instance_eval, I didn't know that it can be used to execute a block with the ampersand. Thanks a lot for your answer!
I am very happy to can help you, because I'm learning metaprogramming now, and I could use some of new knowledge with success. :) About the use of ampersand, I learned a lot of method/proc calls details here. I hope it can be useful to you, too.
This link really is helpfull for me, thank's again :) I found another link here which could probably helpful, about passing arguments if a block is called this way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.