ruby
35 lines · 7 steps
Building safe shell commands in Ruby
An ArchiveBuilder assembles a tar command from parts, escapes it, and runs it while checking the exit status.
Explained by
highlit
1require "shellwords"
2require "open3"
3
4module Backup
5 class ArchiveBuilder
6 def initialize(source_dir, destination:, exclude: [])
7 @source_dir = source_dir
8 @destination = destination
9 @exclude = exclude
10 end
11
12 def call
13 stdout, stderr, status = Open3.capture3(build_command)
14 unless status.success?
15 raise "tar failed (#{status.exitstatus}): #{stderr.strip}"
16 end
17 stdout
18 end
19
20 private
21
22 def build_command
23 parts = ["tar", "--create", "--gzip"]
24 parts.concat(exclude_flags)
25 parts << "--file" << @destination
26 parts << "--directory" << @source_dir
27 parts << "."
28 Shellwords.join(parts)
29 end
30
31 def exclude_flags
32 @exclude.flat_map { |pattern| ["--exclude", pattern] }
33 end
34 end
35end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Assembling commands as an array and joining with Shellwords avoids injection from unescaped paths or patterns.
- 2Open3.capture3 gives you stdout, stderr, and exit status separately so you can react to failures precisely.
- 3Always check status.success? rather than trusting a subprocess to have done its job silently.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 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
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
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/building-safe-shell-commands-in-ruby-explained-ruby-6eaf/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.