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
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
ruby
class ApplicationController < ActionController::Base EXPERIMENTS = { checkout_button_color: %w[control blue green], onboarding_flow: %w[control streamlined]
How A/B test cohorts are assigned in Rails
a-b-testing
cookies
hashing
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.