ruby
39 lines · 8 steps
Guaranteeing cleanup with begin/ensure in Ruby
Two small patterns that use ensure to run cleanup code whether the work succeeds or blows up.
Explained by
highlit
1module FileResource
2 # Opens a file, yields it to the caller, and guarantees the
3 # handle is closed even if the block raises an exception.
4 def self.open(path, mode = "r")
5 handle = File.open(path, mode)
6 begin
7 yield handle
8 ensure
9 handle.close unless handle.closed?
10 end
11 end
12end
13
14class Transaction
15 def initialize
16 @committed = false
17 @actions = []
18 end
19
20 def perform(&action)
21 @actions << action
22 begin
23 action.call
24 yield if block_given?
25 @committed = true
26 ensure
27 rollback unless @committed
28 end
29 end
30
31 private
32
33 def rollback
34 @actions.reverse_each do |a|
35 a.respond_to?(:undo) ? a.undo : nil
36 end
37 @actions.clear
38 end
39end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1An ensure clause runs on both normal exit and exception, making it the right home for cleanup.
- 2Yielding a resource to a caller's block lets the method own acquisition and release while the caller owns usage.
- 3Tracking a success flag lets ensure distinguish a clean finish from a failure that needs undoing.
Related explainers
ruby
class ToastBroadcaster include ActionView::RecordIdentifier def self.broadcast_to(user, message:, type: :notice)
How Turbo Stream toasts broadcast in Rails
turbo-streams
service-object
real-time
Intermediate
6 steps
php
<?php namespace App\Console\Commands;
Releasing stale document locks in Laravel
artisan-command
transactions
row-locking
Intermediate
6 steps
ruby
class TemplateInterpolator PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/ def initialize(strict: false)
Interpolating templates with dotted keys in Ruby
regex
string-interpolation
hash-traversal
Intermediate
6 steps
ruby
class KeyTransformer def self.camelize(data) new.camelize(data) end
Recursively camelizing nested Ruby data
recursion
data-transformation
pattern-matching
Intermediate
7 steps
typescript
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common'; import { Observable, catchError, concatMap, finalize } from 'rxjs'; import { DataSource, QueryRunner } from 'typeorm';
Wrapping requests in a transaction with NestJS
interceptors
transactions
rxjs
Advanced
7 steps
ruby
module Paginatable extend ActiveSupport::Concern private
A reusable pagination concern in Rails
pagination
concerns
http-headers
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/guaranteeing-cleanup-with-begin-ensure-in-ruby-explained-ruby-af12/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.