Skip to content

Instantly share code, notes, and snippets.

@virtualstaticvoid
Last active September 24, 2015 14:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save virtualstaticvoid/762526 to your computer and use it in GitHub Desktop.
Save virtualstaticvoid/762526 to your computer and use it in GitHub Desktop.
Emulates a C# 'using' statement in Ruby
require 'kernel_using'
class ResourceConsumer
def open()
puts 'Opening up...'
end
def close()
puts 'Closing up...'
end
# method for performing clean up
def cleanup()
close()
end
end
using ResourceConsumer.new do |obj|
obj.open
# some work
puts 'Doing work...'
raise 'Some error...'
# 'obj' will automatically cleaned up when the block completes
# even if an exception occurred
end
module Kernel
def using(obj, &block)
begin
block.call(obj)
ensure
obj.cleanup if obj.respond_to? :cleanup
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment