Skip to content

Instantly share code, notes, and snippets.

@jroesch
Created May 15, 2014 01:55
Show Gist options
  • Select an option

  • Save jroesch/023ff3c78878795fe0c8 to your computer and use it in GitHub Desktop.

Select an option

Save jroesch/023ff3c78878795fe0c8 to your computer and use it in GitHub Desktop.
Finalization in Ruby
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