问题描述
具体来说,我想要一个守卫:在初始化时调用特定函数的东西,并在作用域退出时调用另一个特定函数。
解决方法
最好明确地这样做:
class Guard
def initialize
# Init things here
end
def close
# clean up things here
end
end
def my_method
guard = Guard.new
# do things here
ensure
guard.close
end
然后一个常见的模式是使用 yielding 方法提供更好的界面。在使用外部资源时,您会注意到在标准库中经常看到这一点:
class Guard
def self.obtain
guard = new
yield guard
ensure
guard.close
end
# ...
end
Guard.obtain do |guard|
# do things
end
当然,如果消费者不应该与其交互,则产生实际的资源对象是可选的。