Created
May 15, 2014 01:55
-
-
Save jroesch/023ff3c78878795fe0c8 to your computer and use it in GitHub Desktop.
Finalization in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def Object.finalize_with(*ivars_names, &block) | |
| old_init = instance_method(:initialize) | |
| define_method :initialize do |*args| | |
| puts "MyBlock: #{block}" | |
| old_init.bind(self).call(*args) | |
| ivars = ivars_names.map { |ivar| instance_variable_get(ivar) } | |
| ObjectSpace.define_finalizer(self, proc { block.call(*ivars) }) | |
| end | |
| end | |
| class MyFoo | |
| def initialize(count) | |
| @shout_t = count | |
| end | |
| finalize_with :@shout_t do |shout_t| | |
| puts shout_t | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment