Last active
September 24, 2015 14:28
-
-
Save virtualstaticvoid/762526 to your computer and use it in GitHub Desktop.
Emulates a C# 'using' statement 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
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 |
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
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