Sunday, April 3, 2011

Execute code at end of Module/Class, like Ruby test/unit

Ruby's unit testing framework executes unit tests even though nobody creates unit test object. For example,

in MyUnitTest.rb

require 'test/unit'

class MyUnitTest < Test::Unit::TestCase
    def test_true
        assert true
    end
end

and when i invoke that script as

ruby MyUnitTest.rb

test_true method gets executed automatically. How is this done?

I am trying to come up with a framework that can do similarly. I dont want "if __ FILE __ == $0" at the end of every module that uses my framework.

thanks.

From stackoverflow
  • Test::Unit uses at_exit for this, which runs code immediately before your application quits:

    at_exit do
      puts "printed before quit"
    end
    
    .. other stuff
    

    I don't think there is any way to run code specifically after a class or module definition is closed.

    rampion : but you can redefine `Class.inherited` for your class to get references to all the subclasses, and then play with them in your `at_exit` hook.
  • Similar to Daniel Lucraft's answer, you could define a finalizer guard to have some code run when the garbage collector runs:

    ObjectSpace.define_finalizer(MyClass, lambda {
      puts "printed before MyClass is removed from the Object space"
    })
    

    But personally I think at_exit is a better fit since its timing is a bit more deterministic.

0 comments:

Post a Comment