<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tilo Sloboda on Medium]]></title>
        <description><![CDATA[Stories by Tilo Sloboda on Medium]]></description>
        <link>https://medium.com/@tilo-sloboda?source=rss-e3182782ff7e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*shZyFGyhEStMQLg6</url>
            <title>Stories by Tilo Sloboda on Medium</title>
            <link>https://medium.com/@tilo-sloboda?source=rss-e3182782ff7e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 21:06:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tilo-sloboda/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[SmarterCSV 1.15.2: Faster Than Raw CSV Arrays — Benchmarks, ZSV, and the Full Pipeline]]></title>
            <link>https://tilo-sloboda.medium.com/smartercsv-1-15-2-faster-than-raw-csv-arrays-benchmarks-zsv-and-the-full-pipeline-2c12a798032e?source=rss-e3182782ff7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c12a798032e</guid>
            <category><![CDATA[csv]]></category>
            <category><![CDATA[csv-file]]></category>
            <category><![CDATA[csv-import]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[rails]]></category>
            <dc:creator><![CDATA[Tilo Sloboda]]></dc:creator>
            <pubDate>Fri, 20 Feb 2026 09:07:51 GMT</pubDate>
            <atom:updated>2026-02-20T21:51:29.819Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A deep dive into moving the full transformation pipeline into C, and what end-to-end benchmarks reveal.</em></p><blockquote><strong>With the 1.15.x series, SmarterCSV is no longer just more convenient than Ruby’s CSV</strong> —<strong> for end-to-end pipelines SmarterCSV is materially faster!</strong></blockquote><p>If your Rails app imports CSV files — especially customer-provided files of unknown quality — this post is written specifically for you.</p><p>SmarterCSV 1.15.2 is out, and the headline numbers are significant.</p><p>With more than 19.2M downloads, 1.15.2 is the biggest performance release in its history. The headline numbers, measured across 16 different real world benchmark files, each with distinguishing patterns of inputs that need special handling.</p><ul><li><strong>1.6× to 7.2× faster than </strong><strong>CSV.read </strong>which returns raw arrays with no processing</li><li><strong>6× to 113× faster than Ruby’s </strong><strong>CSV.table</strong> (equivalent output)</li><li><strong>5.4× to 37.4× faster than SmarterCSV 1.14.4</strong> (with C-acceleration)<br>- A 50k-row, 62MB CSV with quoted fields: <strong>8.4 seconds → 0.23 seconds<br>- </strong>A 500-column wide CSV: <strong>19.4 seconds → 1.5 seconds<br>- </strong>Files with many empty fields: <strong>12.1× faster</strong></li><li><strong>1.4× to 9.5× faster than SmarterCSV 1.14.4</strong> (without C-acceleration, pure Ruby path)</li></ul><p><strong>What this means in practice:</strong> ETL and data pipelines finish in under 1/4 of a second instead of 8–25 seconds — the difference between a background job that blocks and one that completes before anyone notices. Messy customer-provided files — empty rows, inconsistent quoting, wide schemas — see the biggest gains. High-volume concurrent processing benefits from lower Garbage Collection (GC) pressure across your whole process. And no code changes required to get any of it.</p><p>But before we get into <em>how</em>, it’s worth talking about <em>why SmarterCSV exists at all</em> — because it shapes everything about what we’re optimizing for, and it also explains why most CSV benchmarks you’ll find online are measuring the wrong thing.</p><h3>What SmarterCSV Actually Is</h3><p>SmarterCSV is not a CSV parser in the traditional sense. It’s a <strong>production-oriented CSV ingestion tool</strong>.</p><p>This distinction explains the results you will see in production.</p><p>A CSV parser takes text and tokenizes it — it breaks a string into raw fields. Instead, SmarterCSV takes CSV data and returns something your Rails code can use directly — no post-processing required:</p><pre><br>File.read(users.csv)<br># =&gt; &quot;First Name, Age, Role, Mood,  City \n   Alïcè  ,  32 , admin ,\t😊\n&quot;<br><br>data = SmarterCSV.process(&#39;users.csv&#39;)<br># =&gt; [{ first_name: &quot;Alïcè&quot;, age: 32, role: &quot;admin&quot;, mood: &quot;😊&quot;}, ...]</pre><p>An arrays of hashes. Symbol keys. Numeric types converted. Whitespace stripped. Empty values removed. Empty rows skipped. Duplicate headers handled. Missing headers prefixed. All of that happens automatically.</p><p>That “simple” result reflects a deliberate philosophy with six pillars:</p><ol><li><strong>Hash output</strong> — CSV rows become { first_name: &quot;Alice&quot;, age: 32 }, not [&quot;Alice&quot;, 32]. Named fields, not positional guesswork — directly usable by your code.</li><li><strong>Lenient by default</strong> — This is the one that’s often overlooked. SmarterCSV is not designed to be a strict RFC-4180 validator. It’s designed to parse the majority of CSV files encountered in production, recover gracefully from irregular quoting, infer intent where practical, and avoid requiring flags for common irregularities.</li><li><strong>Intelligent defaults</strong> — The most common transformations (strip whitespace, symbolize keys, convert numerics) happen without configuration. Missing headers are auto-detected and prefixed rather than silently dropping data.</li><li><strong>Chunking</strong> — Large files can be processed in configurable batches, keeping memory bounded regardless of file size. Chunks map naturally to parallel processing with Sidekiq, Resque, or any background job framework.</li><li><strong>Performance</strong> — End-to-end speed, from raw CSV bytes to clean ready-to-use Ruby hashes. Measuring the full pipeline, not just the initial tokenization step.</li><li><strong>Configurability</strong> — Deep options for edge cases: custom separators, key mapping, value converters, selective numeric conversion, and more.</li></ol><p><strong>Lenient by default</strong> is why SmarterCSV exists. Customer-provided CSV files are messy. They have inconsistent quoting, extra whitespace, empty rows, varying encodings, and columns without headers. A strict parser throws an exception the moment it encounters an irregularity — your job fails, and you’re now manually hunting down the offending file. In production, recoverable quirks shouldn’t cause interruptions. SmarterCSV absorbs the mess so your application doesn’t have to — and so you don’t have to write boilerplate post-processing for every single import use case.</p><h3>Understanding End-to-End CSV Performance</h3><p>Most CSV benchmarks measure <strong>tokenization</strong> — the time it takes to split a file into fields. That’s useful for evaluating parsers. For production ingestion pipelines, the full picture includes what happens next.</p><p>After tokenization, a real application still needs to:</p><ul><li>Build hashes (not just arrays)</li><li>Symbolize keys</li><li>Strip whitespace from keys and values</li><li>Convert numeric strings to integers and floats</li><li>Remove empty values and blank rows</li><li>Handle duplicated or missing headers</li><li>Apply key mapping for schema normalization</li></ul><p>All of that work happens <em>after</em> tokenization. And as we’ll show, it often dwarfs the parsing cost.</p><h3>The ZSV lesson</h3><p><a href="https://github.com/liquidaty/zsv">zsv-ruby</a> is genuinely impressive engineering — a CSV parser written in C with SIMD acceleration (SSE2, AVX2, AVX-512, and ARM NEON). Its raw tokenizer is extraordinarily fast.</p><p>Before building 1.15.2, we profiled the full pipeline — parsing plus transformation — alongside zsv-ruby. The results were instructive.</p><p>In benchmarks against the earlier SmarterCSV 1.15.1, ZSV’s raw parser was 8 to 22× faster on tokenization alone. But raw tokenization is rarely or perhaps even never what you need in production. We built a ZSV+transformations benchmark — ZSV with the same post-parse data cleaning any real application needs: symbol keys, whitespace stripping, numeric conversion, empty value removal — and profiled where that time was actually going.</p><p>The answer was striking: <strong>80–92% of total ZSV+transformations execution time was spent in the Ruby transformation layer</strong> — the kind of post-processing <strong>code you’d have to write yourself</strong> to make the data usable — not in the SIMD C parser at all.</p><p>That surprising finding made the path forward obvious. The lesson from ZSV wasn’t “add SIMD” It was: <strong>“do the entire pipeline in C”</strong> The tokenizer was not the bottleneck — the transformation / data normalization was.</p><p>That’s what 1.15.2 fixes — and we’ll show the head-to-head results against ZSV+transformations later, once we’ve covered what changed.</p><h3>Where 1.15.1 Was Slow: Profiling the Real Bottleneck</h3><p>When we profiled SmarterCSV 1.15.1 (the bugfix release that followed 1.15.0’s major C parser work), the breakdown looked like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*rs5RqphfSR3TtY7WkJWhQQ.png" /><figcaption>Performance Profile before Phase 2 Improvements</figcaption></figure><p>Our <a href="https://medium.com/@tilo-sloboda/smartercsv-1-15-0-2-4-faster-ruby-csv-processing-up-to-20-in-edge-cases-669d80a30588">existing C-extension</a> was already doing excellent work on tokenization. But after every row, it handed a partially-built hash back to Ruby, and Ruby iterated over it <em>again</em> to apply transformations. Two passes. Ruby object allocations on every field of every row.</p><p>On many_empty_fields_20k.csv, hash_transformations consumed <strong>87% of total processing time</strong>. On fmap.csv, it was around 85%. These aren&#39;t edge cases — they&#39;re representative of what customer-provided CSV files look like: lots of blank fields, lots of values that need cleaning.</p><p>The solution was unambiguous: <strong>move the entire transformation pipeline into C, executing field-by-field during parsing</strong>, so we never build an untransformed intermediate hash at all.</p><h3>What We Built: The 1.15.2 C-Extension</h3><h3>A unified field pipeline</h3><p>Previously, the C-extension’s field-insertion logic was duplicated across four call sites: fast-path loop body, fast-path last field, slow-path loop body, slow-path last field. Each applied some subset of transformations inconsistently.</p><p>The refactor now passes all transformation configuration options into C at parse time. Every field passes through a well-defined, single-pass pipeline:</p><p><strong>Step 1 — Blank check.</strong> Scans the raw bytes for all-whitespace content (\r, \n, \t, space, \v, \f), matching Ruby&#39;s blank? behavior exactly. If blank, either inserts a shared empty string or skips entirely, depending on remove_empty_values.</p><p><strong>Step 2 — Empty field.</strong> A zero-length field is handled and either inserted or skipped.</p><p><strong>Step 3 — Quoted field.</strong> Unescapes in place and inserts.</p><p><strong>Step 4 — Zero-value check.</strong> This one has an interesting design choice worth explaining.</p><p>Instead of converting to a number first and then checking == 0, the zero check runs as a <strong>string-based scan</strong> on the raw bytes, matching the pattern /\A0+(?:\.0+)?\z/ — catching &quot;0&quot;, &quot;00&quot;, &quot;0.0&quot;, &quot;00.00&quot; and so on. This happens <em>before</em> any numeric conversion and <em>before</em> any Ruby object is allocated.</p><p>The benefit: remove_zero_values: true works correctly even when convert_values_to_numeric: false. And filtered values never make it to the Ruby heap at all — the check runs on C bytes and if it matches, we just move on to the next field.</p><p><strong>Step 5 — Numeric conversion.</strong> strtol/strtod with only:/except: mode support for selective column conversion.</p><p><strong>Step 6 — String fallback.</strong> If none of the above applied, create the Ruby string.</p><p>The result: every field is fully transformed in one pass through C. The hash_transformations Ruby method is never called when the C path is active.</p><h3>Lazy hash allocation</h3><p>A smaller but meaningful optimization: <strong>the output hash is no longer allocated eagerly per row</strong>.</p><p>Previously, a hash was allocated for every row upfront — even rows where all fields turned out to be blank or zero, and would be discarded entirely by remove_empty_hashes: true. That&#39;s wasted allocation work on every skipped row.</p><p>Now we defer hash creation until we know there’s actually data worth keeping. We process the fields first, apply the transformations, and only allocate the hash when the first insertable field is confirmed. We also give the compiler a hint that allocation is the rare case — only triggered on the very first field that survives filtering — enabling better branch prediction on the hot path.</p><p>For files with lots of empty or filtered rows — exactly the messy customer-provided files SmarterCSV is built for — this eliminates heap allocation and GC registration for every skipped row.</p><h3>One more Ruby-level optimization</h3><p>After implementing C-level transformations, profiling still showed a surprising amount of time in the Ruby layer — specifically in detect_multiline, which counted quote characters on every line to determine whether a field spanned multiple rows.</p><p>The fix was a single guard clause: <strong>skip quote counting entirely when the line contains no quote character</strong>. Most lines in most CSV files are unquoted. Calling into C to count quotes on every one of them was pure overhead.</p><pre>return false unless line.include?(quote_char) # huge gain!</pre><p>This eliminates the Ruby→C bridge crossing for quote detection on the majority of lines — and the impact was larger than expected: <strong>1.3× to 2.1× additional speedup</strong> on the accelerated path, on top of the C transformation gains. This optimization <strong>benefits both the accelerated and pure Ruby paths.</strong></p><h3>What stays in Ruby (and why)</h3><p>Three things deliberately remain in Ruby:</p><p><strong>remove_values_matching</strong> — user-provided Ruby Regexp. Pulling Ruby&#39;s oniguruma regex engine into C would be substantial complexity for an infrequently-used feature.</p><p><strong>value_converters</strong> — user-supplied Ruby lambdas or procs. These execute in Ruby by definition.</p><p><strong>key_mapping nil-key cleanup</strong> — keys mapped to nil are removed post-C via a Ruby Hash#delete loop. Fast enough at scale that a C implementation isn&#39;t warranted.</p><p>The C-accelerated path skips hash_transformations entirely — there is no double-pass. The pure-Ruby fallback path (for JRuby, or when the C extension is unavailable) still calls hash_transformations unchanged, so nothing breaks.</p><h3>Test coverage</h3><p>SmarterCSV already has extensive test coverage built up over 14 years of production use. Before shipping 1.15.2, we added 32 new tests covering: numeric conversion (integers, floats, signed, bignum, non-numeric strings), only:/except:selective conversion, remove_zero_values with string zeros independent of numeric conversion, remove_empty_values with blank and whitespace-only fields, remove_empty_hashes with all-blank and all-filtered rows, combined transformations, and C/Ruby parity verification across 7 option combinations.</p><p>Full suite: <strong>720 tests, 0 failures</strong>. Coverage: 100%.</p><h3>The Benchmark Results</h3><p>All benchmarks: Ruby 3.4.7, Apple M1 (arm64-darwin25). Best of 3 timed iterations after 1 warm-up.</p><h3>1.14.4 → 1.15.1 → 1.15.2: the full picture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*Qdi43LkHwJ4h0gemlY-s_A.png" /><figcaption>Performance Comparison against 1.15.2 Improvements</figcaption></figure><p>The three-version table tells the story of two distinct phases of optimization, and reading it column-by-column is illuminating.</p><p><strong>fmap.csv</strong> barely moved from 1.14.4 to 1.15.1 (0.748s → 0.763s — essentially unchanged), then dropped sharply in 1.15.2 (→ 0.079s, <strong>9.5×</strong>). The 1.15.0 C-parser gave this file almost nothing because its bottleneck was never tokenization — it was transformation. Our improvements worked.</p><p><strong>many_empty_fields_20k</strong> tells the same story more starkly: 1.15.1 barely improved over 1.14.4 (0.413s → 0.386s), then 1.15.2 took it to 0.034s — a <strong>11.4× gain from 1.15.1 alone</strong> — because 87% of its processing time was hash_transformations on empty values that now never reach Ruby at all.</p><p><strong>long_fields_20k</strong> shows the reverse: most of the gain came in 1.15.0 (3.054s → 0.167s, an 18× improvement from the C-parser&#39;s memchr fast path on large fields), and 1.15.2 adds only 1.5× on top. The bottleneck there was always parsing, not transformation.</p><p><strong>PEOPLE_IMPORT_C.csv</strong> (the most important benchmark for Rails import workloads — 50k rows, 62MB, heavily quoted, many columns) goes: 8.4s → 2.4s → 0.23s. The cumulative <strong>37.4× improvement </strong>from 1.14.4 means an import that used to take the better part of 10 seconds now completes in under a quarter of a second.</p><h3>Where does the remaining time go in 1.15.2?</h3><p>After we moved the transformations into C, the profile looked like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*9YBJd8kEjEVp1XxMCc-dLw.png" /><figcaption>Performance Profile before reduction of unnecessary Ruby-&gt;C calls</figcaption></figure><p>In the next step we removed unnecessary Ruby→C calls for Quote counting, and the overhead dropped from ~11% to ~5% of total time, while overall processing time fell another 1.3×–2.1×.</p><p>The profile is now clean. wide_500_cols_20k.csv is dominated by C parsing — many hash insertions per row. embedded_newlines_20k.csv keeps more time in Ruby IO because multiline field reassembly still happens in Ruby. Those are the natural next frontiers.</p><h3>Transformations in C Are Free — Sometimes Faster Than Disabled</h3><p>One surprising benchmark result deserves a special call-out. When measuring 1.15.2 <strong>with acceleration, but disabling transformations</strong> via the options, the results are counterintuitive:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*7Tp2uED0fdEYkxi-esfEoQ.png" /><figcaption>Accelerated 1.15.2 Results when disabling transformations via options</figcaption></figure><p>Enabling transformations is not just free — in several cases it actively speeds things up. The reason: filtering empty values and empty hashes in C means fewer Ruby objects are created and pushed onto the heap in the first place. Less allocation means less GC pressure, which means less total work for the Ruby runtime. The transformation step pays for itself.</p><h3>Compared to Ruby’s Built-in CSV</h3><p>For this we were doing two comparisons:</p><ol><li>against <strong>CSV.table(file).map(&amp;:to_h)</strong> which returns arrays of hashes.</li><li>against <strong>CSV.read</strong>, which returns arrays of arrays — no post-processing</li></ol><blockquote><strong>SmarterCSV 1.15.2 is now 1.6× to 7.2× faster than CSV.read</strong></blockquote><h4>SmarterCSV 1.15.2 vs CSV.table (equivalent output: symbol-key hashes)</h4><p>CSV.table(file).map(&amp;:to_h) is the closest equivalent to what SmarterCSV returns: symbol keys, numeric conversion, ready to use. Note that this is already a favorable comparison for Ruby&#39;s CSV — it still won&#39;t strip whitespace or remove empty values — things you&#39;d have to add yourself.</p><blockquote><strong>SmarterCSV does more out of the box and is 6× to 113× faster.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*0Nm4FRhruYqwrxjsG39obQ.png" /><figcaption>SmarterCSV 1.15.2 vs CSV.table</figcaption></figure><p>The extreme gaps on PEOPLE_IMPORT_C (113×) and wide_500_cols (41×) reflect that CSV.table handles complex quoting and wide schemas particularly poorly.</p><h4>SmarterCSV 1.15.2 vs CSV.read (raw arrays — no processing)</h4><p>CSV.read returns raw arrays with no transformation — no symbol keys, no numeric conversion, no whitespace stripping. SmarterCSV does all of that and is still 1.6× to 7.2× faster.</p><blockquote><strong>SmarterCSV 1.15.2 is now 1.6× to 7.2× faster than </strong><strong><em>CSV.read</em></strong></blockquote><p>The reason: Ruby’s CSV library is pure Ruby. SmarterCSV’s C extension uses optimized native code — memchr for fast scanning, pre-sized hash allocation, and single-pass field processing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*8o1rqtbab9_CEtioR1KMOA.png" /><figcaption>SmarterCSV 1.15.2 vs CSV.read</figcaption></figure><h3>The ZSV Comparison: Giving Credit Where It’s Due</h3><p><a href="https://github.com/liquidaty/zsv">zsv-ruby</a> wraps a hand-optimized CSV parser that uses SIMD acceleration on SSE2, AVX2, AVX-512, and ARM NEON — simultaneously scanning up to 64 bytes at once for delimiter, newline, and quote characters. The engineering is excellent and the raw parser speed is genuinely impressive.</p><p>We built a ZSV+transformations benchmark — ZSV with the same transformations SmarterCSV performs: symbol keys, whitespace stripping, numeric conversion, empty value removal, empty hash removal, duplicate header suffixing, and missing header prefixing. This represents the work any real application would need to add on top of ZSV to get equivalent output.</p><blockquote>Note: zsv-ruby 1.3.1 has a GC marking bug on Ruby 3.4.x that disables GC during ZSV calls — giving ZSV a structural advantage in these benchmarks. SmarterCSV wins 14 of 16 files.</blockquote><p>With all of that said, here is the head-to-head on equivalent output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*CVfY2pijcb0EXwFuHzTavQ.png" /><figcaption>Equivalent Output Comparison: ZSV-Ruby 1.3.1 vs SmarterCSV 1.15.2</figcaption></figure><p><strong>SmarterCSV wins 14 of 16 files</strong>, including the complex, heavily-quoted, and wide files most representative of real import workloads. The margin is particularly large on the files that matter most for Rails apps: <strong>6.34×</strong> on PEOPLE_IMPORT_C, <strong>3.34×</strong> on wide_500_cols.</p><p>ZSV+transformations wins on two cases where its raw speed advantage comes through cleanly: long_fields_20k (SIMD&#39;s byte-scanning advantage is most visible on large, simple fields), embedded_newlines_20k.</p><h3>What This Means for Your Rails App</h3><p><strong>ETL and data pipelines</strong> — Files that used to take 8–25 seconds now take under 250ms. That’s the difference between a background job that blocks and one that completes before anyone notices.</p><p><strong>Customer-provided CSV imports</strong> — SmarterCSV is built specifically for messy, real-world files: inconsistent quoting, mixed whitespace, empty rows, unknown column counts, columns without headers. Those are exactly the cases where hash_transformations was doing the most work, and where 1.15.2 gains the most. The lazy hash allocation helps here specifically — rows filtered out by remove_empty_hashes: true never trigger a heap allocation.</p><p><strong>Wide schemas</strong> — ERP exports, analytics dumps, B2B data feeds with hundreds of columns see dramatic gains: 12.9× vs 1.14.4 on a 500-column file, and 41× faster than CSV.table on the same workload.</p><p><strong>High-volume concurrent processing</strong> — Fewer allocations per row means less garbage collection (GC) pressure across your whole process. In applications running multiple concurrent imports, this compounds.</p><h3>No C Extension? You Still Get Up to 9.5× Faster</h3><p>The C acceleration path gets the headline numbers, but SmarterCSV also supports a pure Ruby path (acceleration: false) for JRuby users and platforms where the C extension is unavailable. 1.15.2 includes significant optimizations here too.</p><p>The biggest win: when a line contains no quote characters, the character-by-character parsing loop is replaced entirely by Ruby’s String#split— a single C call that replaces thousands of Ruby-level iterations. Combined with several other targeted improvements (skipping redundant passes, faster blank detection, pre-computed option hashes), the Ruby-only path sees substantial gains across the board:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*MGDGQB8alnrab_IWLA6OHw.png" /><figcaption>Ruby-only Performance Improvements</figcaption></figure><p><strong>4× to 9.5× faster than 1.14.4 on the pure Ruby path.</strong> Files with mostly<br>unquoted fields see the largest gains. Heavily quoted files (embedded newlines, heavy quoting, embedded separators) still improve 1.5×–2× from the other optimizations. JRuby users get a meaningful upgrade without touching the C layer.</p><h3><strong>Benchmark Reproducibility</strong></h3><p>Some of the benchmark files used in this article contain production data and cannot be shared publicly. All benchmarks were run on Ruby 3.4.7, Apple M1 (arm64-darwin25), with 1 warmup iteration and 3 measured iterations (median reported).</p><p>We encourage you to benchmark SmarterCSV on your own CSV files. Real-world data varies — wide schemas, heavy quoting, many empty fields, and unusual encodings all affect performance differently.</p><p>If you find interesting results, share them in the comments or open a GitHub <a href="https://github.com/tilo/smarter_csv/discussions">discussion</a> or <a href="https://github.com/tilo/smarter_csv/issues">issue</a>. Your data shapes what we optimize next.</p><h3>Future Work</h3><p>The optimizations in 1.15.2 already delivered on much of what was on the roadmap — including eliminating the Ruby→C bridge overhead for quote counting, which alone contributed 1.3×–2.1× on the accelerated path. The remaining Ruby overhead is now smaller than initially projected.</p><p>There are still clear architectural paths to reduce it further, with some file types standing to gain considerably more. Once the C layer dominates total processing time on most files, SIMD acceleration of the parser itself — the approach zsv pioneered so effectively — becomes a meaningful target rather than a distraction. Future improvements could still outshine the impressive gains of today’s 1.15.2.</p><p>There’s more to come.</p><h3>Upgrade</h3><pre># Gemfile<br>gem &#39;smarter_csv&#39;, &#39;~&gt; 1.15.2&#39;</pre><p>No API changes. No new configuration required. Existing code works as-is.</p><ul><li>Full benchmark data and implementation notes: <a href="https://github.com/tilo/smarter_csv/pull/319">PR #319</a></li><li>Source, changelog, documentation: <a href="https://github.com/tilo/smarter_csv">github.com/tilo/smarter_csv</a></li></ul><p>If you process unusual CSV files — wide schemas, messy encoding, heavy quoting, lots of empty fields — try it and share your results in the comments or as a GitHub discussion. Real-world data shapes what we optimize next.</p><p><em>SmarterCSV is open source. If it’s saving you time or infrastructure cost, a ⭐ on the repo helps other developers find it.</em></p><p>Check it out on GitHub ⭐<br><a href="https://github.com/tilo/smarter_csv">https://github.com/tilo/smarter_csv</a><br><a href="https://github.com/tilo/smarter_csv/blob/main/CHANGELOG.md">https://github.com/tilo/smarter_csv/blob/main/CHANGELOG.md</a></p><p><em>Companies processing millions of rows in production are already seeing these gains. If SmarterCSV is saving your team real time and infrastructure cost, consider becoming a </em><a href="https://github.com/sponsors/tilo"><em>GitHub Sponsor</em></a><em> — it directly supports continued development, including the future work described above. Every sponsor makes the next release more likely.</em></p><p><em>Previously: </em><a href="https://medium.com/@tilo-sloboda/smartercsv-1-15-0-2-4-faster-ruby-csv-processing-up-to-20-in-edge-cases-669d80a30588"><em>SmarterCSV 1.15.0: 2–4× Faster Ruby CSV Processing</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c12a798032e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SmarterCSV 1.15.0: 2–4× Faster Ruby CSV Processing (Up to 20× in Edge Cases)]]></title>
            <link>https://tilo-sloboda.medium.com/smartercsv-1-15-0-2-4-faster-ruby-csv-processing-up-to-20-in-edge-cases-669d80a30588?source=rss-e3182782ff7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/669d80a30588</guid>
            <category><![CDATA[csv]]></category>
            <category><![CDATA[csv-import]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Tilo Sloboda]]></dc:creator>
            <pubDate>Fri, 06 Feb 2026 08:20:11 GMT</pubDate>
            <atom:updated>2026-02-20T09:09:11.724Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>SmarterCSV 1.15.0: 2–4× Faster Ruby CSV Processing</strong></h3><h3><strong>🔥 Update: </strong><a href="https://tilo-sloboda.medium.com/smartercsv-1-15-2-faster-than-raw-csv-arrays-benchmarks-zsv-and-the-full-pipeline-2c12a798032e"><strong>Even Bigger Performance Gains in 1.15.2</strong></a></h3><h3>Big Wins in performance — faster and leaner CSV processing</h3><p>I’m excited to share the release of <strong>SmarterCSV 1.15.0</strong> — a major performance milestone for Ruby CSV processing.</p><p>This release focuses on <strong>speed, efficiency, and real-world usability</strong>. Whether you’re processing tens of thousands of rows or tackling huge CSV files, 1.15.0 delivers consistently faster performance than both previous SmarterCSV versions and Ruby’s built-in CSV library.</p><h3>Summary</h3><p>Benchmarks on Ruby 3.4.7 (M1 Apple Silicon) show:<br> * 2.6×–3.5× faster vs SmarterCSV 1.14.4<br> * ~3× faster (P90) vs Ruby CSV 3.3.5 hashes<br> * ~7.8× faster (P90) vs CSV.table<br> * +10× faster for specific workloads<br> * 43% fewer object created<br> * 39% less memory allocated</p><p>This release introduces a new high-performance parsing path while preserving API compatibility and RFC-4180 correctness.<br><strong>No tuning required — existing code gets faster by upgrading.</strong></p><p>If you process large CSVs in Ruby (ETL, data pipelines, analytics, imports), the performance improvements should be immediately noticeable.</p><p><strong>Try it out, and let us know how it performs on your datasets!</strong></p><h3>What’s new in 1.15.0</h3><p>SmarterCSV 1.15.0 introduces a number of performance optimizations under the hood, including:</p><ul><li>Faster hash construction with pre-sized buckets</li><li>Inline whitespace handling in C</li><li>Improved newline and quoting handling</li><li>A memchr fast path for unquoted fields</li></ul><p>These changes translate to significant real-world speedups across a wide variety of datasets.</p><h3>New Features</h3><h4><strong>Block Processing with chunk_index</strong></h4><p>When using block-based processing, an optional second parameter chunk_index is now passed to the block. This 0-based index is useful for progress tracking and debugging. The change is backwards compatible - existing code continues to work.</p><pre>SmarterCSV.process(file, chunk_size: 100) do |chunk, chunk_index|<br>  puts &quot;Processing chunk #{chunk_index}...&quot;<br>  Model.import(chunk)<br>end</pre><h4>Exception Improvements</h4><p>Missing keys and duplicate headers now appear clearly in error messages.</p><p>MissingKeys#keys - programmatic access to missing keys without parsing error messages.</p><p>DuplicateHeaders#headers - programmatic access to duplicate headers without parsing error messages</p><pre># Example: accessing missing keys programmatically<br>rescue SmarterCSV::MissingKeys =&gt; e<br>  e.keys  # =&gt; [:employee_id, :department]<br>end<br><br># Example: accessing duplicate headers programmatically<br>rescue SmarterCSV::DuplicateHeaders =&gt; e<br>  e.headers  # =&gt; [:email]<br>end</pre><h3>Memory Efficiency</h3><p>SmarterCSV 1.15.0 also reduces allocation overhead:</p><ul><li><strong>39% less memory allocated</strong></li><li><strong>43% fewer objects created</strong></li></ul><h3>Performance Details 📊</h3><p>Benchmarks were run on <strong>Ruby 3.4.7</strong> on Apple Silicon (<strong>M1</strong>). All times are in seconds.</p><p>CSV parsing is one of the most common bottlenecks in data workflows. Many benchmarks focus on <em>raw tokenization</em>, which only tells part of the story. In real applications you still need to build hashes, normalize keys, convert types, and handle edge cases like embedded newlines or quoting.</p><p>SmarterCSV already returns ready-to-use hashes with symbol keys and type conversion — and now 1.15.0 does it <strong>much faster</strong>.</p><blockquote>Beware of comparisons that focus solely on raw CSV parsing. Such benchmarks measure only tokenization, while real-world usage still requires substantial post-processing. Omitting that work consistently understates the true cost of CSV ingestion.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*YeXLp-4I8DYbJBpi57aQnw.png" /><figcaption>See Details Below</figcaption></figure><p>And all of this while returning fully usable hashes with conversions — not just raw arrays.</p><p><strong>Try it out, and let us know how it performs on your datasets!</strong></p><h3>Compared to SmarterCSV 1.14.4</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*YY6hv9G9g5Qp49vr0tq-Lw.png" /><figcaption>SmarterCSV 1.15.0 compareds to 1.14.4</figcaption></figure><h3>Compared to Ruby’s CSV (3.3.5)</h3><p>SmarterCSV returns fully processed data structures; for fair comparison, we benchmark against:</p><ul><li><strong>CSV hashes:</strong> CSV.read(file, headers: true).map(&amp;:to_h)<br>this produces string keys, but there is no type conversion</li><li><strong>CSV.table:</strong> CSV.table(file).map(&amp;:to_h) <br>this produces symbol keys + numeric conversion</li></ul><p>In both cases you will still need post-processing with Ruby CSV, which is not included in this comparison.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wsTm4L7riYjIlSNMNvEt2w.png" /><figcaption>SmarterCSV 1.15.0 compared to Ruby CSV 3.3.5</figcaption></figure><h3>What’s next</h3><p>SmarterCSV continues to evolve with performance and correctness improvements. This release lays the groundwork for even more high-performance parsing capabilities.</p><p>Check it out on GitHub ⭐<br><a href="https://github.com/tilo/smarter_csv">https://github.com/tilo/smarter_csv</a><br><a href="https://github.com/tilo/smarter_csv/blob/main/CHANGELOG.md">https://github.com/tilo/smarter_csv/blob/main/CHANGELOG.md</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=669d80a30588" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Announcing SmarterCSV 1.14.2✨]]></title>
            <link>https://tilo-sloboda.medium.com/announcing-smartercsv-1-14-2-129d1f8329dc?source=rss-e3182782ff7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/129d1f8329dc</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[csv-file]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[csv]]></category>
            <dc:creator><![CDATA[Tilo Sloboda]]></dc:creator>
            <pubDate>Thu, 10 Apr 2025 08:11:26 GMT</pubDate>
            <atom:updated>2025-04-10T16:42:50.153Z</atom:updated>
            <content:encoded><![CDATA[<h4>Fine-Grained Control for Writing CSV Files</h4><p>I’m excited to announce the release of <a href="https://github.com/tilo/smarter_csv">SmarterCSV 1.14.2</a>, which brings significant improvements to the CSV writer functionality! 🎉</p><p>While previous versions of <a href="https://github.com/tilo/smarter_csv">SmarterCSV</a> focused primarily on reading and transforming CSV files, the 1.14.x releases enhance the ability to <a href="https://tilo-sloboda.medium.com/csv-writing-with-smartercsv-26136d47ad0c"><strong>write CSV files with greater control</strong></a><strong>.</strong></p><p>This SmarterCSV::Writer class, now supports:</p><ul><li>automatic inference of headers based on the input data</li><li>automatic quoting of problematic headers or data fields</li><li>customizable header_converter and value_converters to customize headers and data rows.</li><li>mapping of headers</li><li>selecting a sub-set of headers</li><li>simplified interface for easy export of CSV data</li><li>advanced interface for appending data to CSV output</li></ul><p>This allows for both quick &amp; easy CSV export via the simplified interface, as well as handling of custom output formats through advanced options.</p><h3>💡 Learn More</h3><p><strong>Check out examples and feature highlights in these two articles:</strong></p><ul><li>✍️ <a href="https://tilo-sloboda.medium.com/csv-writing-with-smartercsv-26136d47ad0c">Write CSVs with SmarterCSV</a></li><li>📘 <a href="https://tilo-sloboda.medium.com/parsing-csv-files-in-ruby-with-smartercsv-6ce66fb6cf38">Read CSVs with SmarterCSV</a></li></ul><p><a href="https://github.com/tilo/smarter_csv">SmarterCSV</a> continues to evolve — give it a try — and let us know how it’s working for you!</p><p>Check it out on GitHub: <a href="https://github.com/tilo/smarter_csv">https://github.com/tilo/smarter_csv</a> ⭐</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=129d1f8329dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CSV Writing with SmarterCSV]]></title>
            <link>https://tilo-sloboda.medium.com/csv-writing-with-smartercsv-26136d47ad0c?source=rss-e3182782ff7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/26136d47ad0c</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[csv]]></category>
            <category><![CDATA[csv-file]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Tilo Sloboda]]></dc:creator>
            <pubDate>Thu, 10 Apr 2025 07:04:31 GMT</pubDate>
            <atom:updated>2025-04-11T16:34:22.429Z</atom:updated>
            <content:encoded><![CDATA[<h4>Fine-Grained Control for Writing CSV Files</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JeP-n3ncRSU-fJepmGEXSQ.png" /></figure><p><a href="https://github.com/tilo/smarter_csv">SmarterCSV</a> has long focused on <a href="https://medium.com/@tilo-sloboda/parsing-csv-files-in-ruby-with-smartercsv-6ce66fb6cf38">reading CSV files with convenience, efficiency, and robustness </a>— and it can now write CSV files too.</p><p>Just like <a href="https://medium.com/@tilo-sloboda/parsing-csv-files-in-ruby-with-smartercsv-6ce66fb6cf38">reading</a>, writing in <a href="https://github.com/tilo/smarter_csv">SmarterCSV</a> assumes your data is organized as hashes, arrays of hashes — or batches of arrays of hashes. This structure integrates smoothly with ActiveRecord and other modern data stores.</p><p>When writing CSV files, SmarterCSV::Writer automatically discovers all keys in your data and uses them as column headers. This works great out of the box, but for advanced use cases, you may want more control over the output.</p><p>SmarterCSV::Writer offers two writing interfaces:</p><ul><li>the simplified interface</li><li>the full API that gives you more control, and allows you to keep the output open to append more data.</li></ul><p>We use both forms in examples interchangeably, and use version 1.14.2 for the examples.</p><h3>Simplified Interface</h3><pre>SmarterCSV.generate(filename, options) do |csv_writer|<br>  MyModel.find_in_batches(batch_size: 100) do |batch|<br>    # use ActiveRecord to select the relevant keys<br>    batch.pluck(:name, :age, :height).each do |record|<br>      csv_writer &lt;&lt; record<br>    end<br>  end<br><br>end # automatically saves &amp; closes the output</pre><p>This example shows how to limit input records to only specific attributes (:name, :age, :height) using pluck. The writer automatically infers the headers from the data and finalizes the file when the block exits.</p><h3>Full Interface</h3><pre>csv_writer = SmarterCSV::Writer.new(filename, options)<br>csv_writer &lt;&lt; [<br>                [{name: &#39;John&#39;, age: 22, height: &#39;6&quot;1\&#39;&#39;}],<br>                 {name: &#39;Jane&#39;, age: 24, height: &#39;5&quot;8\&#39;&#39;}<br>                ]<br>csv_writer &lt;&lt; {name: &#39;Tina&#39;, age: 21, height: &#39;5&quot;7\&#39;&#39;, pets: &#39;Zoe&#39;}<br>csv_writer.finalize # saves &amp; closes the output explicitly</pre><p>The full interface gives you more control. You can pass around the csv_writer instance to <strong>append data</strong> from different parts of your application. You have to finalize and close the output file explicitly, using the finalize method.</p><p>The resulting CSV file will look like this:</p><pre>name,age,height,pets<br>John,22,&quot;6&quot;&quot;1&#39;&quot;<br>Jane,24,&quot;5&quot;&quot;8&#39;&quot;<br>Tina,21,&quot;5&quot;&quot;7&#39;&quot;,Zoe</pre><p>Do you notice something special? We mixed and matched hashes, arrays of hashes, and even batches — all in the same writer instance. Some records had new keys, some had tricky strings — and <strong>it all just worked</strong>.</p><p>Real-world data can contain unexpected content — <a href="https://github.com/tilo/smarter_csv">SmarterCSV</a> is designed to handle it <strong>robustly</strong>, whether you’re reading or writing CSV files.</p><h3>Key Features of SmarterCSV::Writer</h3><p>This example highlights several powerful features:</p><ul><li><strong>Flexible input formats</strong>: Pass a single hash, an array of hashes, or even nested batches — they’re all flattened automatically.</li><li><strong>Automatic quoting</strong>: Fields with commas, newlines, or special characters are quoted correctly using your chosen quote_char.</li><li><strong>Quote escaping</strong>: If the quote_char itself appears inside a field value, it’s properly escaped.</li><li><strong>Header auto-discovery: </strong>As new keys appear in later rows (e.g., :pets), they&#39;re appended to the CSV headers automatically—this is helpful when working with sparse or evolving data structures.</li></ul><p>If you just need to write your data as-is, you can stop here 😊 — but there’s more..</p><p>Sometimes, you need more control over the structure of your output CSV — especially when integrating with downstream systems or aligning to a specific format.</p><p><a href="https://github.com/tilo/smarter_csv">SmarterCSV</a> gives you the options to fully control your output format — both for the headers and the data rows.</p><h3>Controlling your Headers</h3><p>For manipulating the headers, <a href="https://github.com/tilo/smarter_csv">SmarterCSV</a> gives you that flexibility with several key options:</p><ul><li>✅ Limit headers to a specific subset of keys</li><li>🔁 Rename or map hash keys to custom header names</li><li>🛠 Convert hash keys programmatically</li></ul><h3>Limiting Headers to a Subset</h3><p>You can explicitly set which keys appear in the header using the :headers option:</p><pre>data = [<br>  {name: &#39;Alice&#39;, age: 30, email: &#39;alice@example.com&#39;},<br>  {name: &#39;Bob&#39;, age: 25, email: &#39;bob@example.com&#39;}<br>]<br>options = { headers: [:name, :email] }<br><br>SmarterCSV.generate(&#39;out.csv&#39;, options) do |csv|<br>  csv &lt;&lt; data<br>end</pre><p>Output:</p><pre>name,email<br>Alice,alice@example.com<br>Bob,bob@example.com</pre><h3>Mapping Hash Keys to Custom Header Names</h3><p>Use :map_headers to not only limit which keys are used, but also rename them:</p><pre>data = [<br>  {first_name: &#39;Alice&#39;, age: 30, email: &#39;alice@example.com&#39;},<br>  {first_name: &#39;Bob&#39;, age: 25, email: &#39;bob@example.com&#39;}<br>]<br>options = { map_headers: {first_name: &#39;Name&#39;, email: &#39;Email Address&#39;} }<br><br>SmarterCSV.generate(&#39;out.csv&#39;, options) do |csv|<br>  csv &lt;&lt; data<br>end</pre><p>Output:</p><pre>Name,Email Address<br>Alice,alice@example.com<br>Bob,bob@example.com</pre><p>⚠️ When you provide headers using :map_headers or :headers, SmarterCSV will <strong>disable automatic header discovery</strong> — unless you explicitly tell it otherwise.</p><p>When either of these options is set, SmarterCSV won’t look for additional keys in the input data — so make sure you include all the headers you want up front.</p><p>With :map_headers, it can make sense to manually set discover_headers: true — this way, SmarterCSV will include additional keys from the input alongside your mapped headers.</p><h3>Converting Headers Programmatically</h3><p>Use header_converter to define a lambda to programmatically convert headers:</p><pre>data = [<br>  {first_name: &#39;Alice&#39;, email: &#39;alice@example.com&#39;},<br>  {first_name: &#39;Bob&#39;, email: &#39;bob@example.com&#39;}<br>]<br>options = {<br>  header_converter: -&gt;(header) { header.upcase }<br>}<br>SmarterCSV.generate(&#39;out.csv&#39;, options) do |csv|<br>  csv &lt;&lt; data<br>end</pre><p>Output:</p><pre>FIRST_NAME,EMAIL<br>Alice,alice@example.com<br>Bob,bob@example.com</pre><h3>Controlling your Data Format</h3><p>Sometimes, you want to control how your data <strong>values</strong> appear in the CSV output — not just the headers.</p><p>SmarterCSV gives you flexible options for manipulating your data rows:</p><ul><li>🧩 Choosing your own row or column separators</li><li>❝ Force-quoting the values in each row</li><li>🛠 programmatically converting values for specific fields</li><li>🔧 programmatically converting values for all fields</li></ul><h3>Choosing Your Row and Column Separators</h3><p>The defaults set the row separator to the default on your computer, e.g. \n on Mac or Linux, and the column separator to , — you can override them:</p><pre>data = [{name: &#39;Alice&#39;, city: &#39;New York&#39;}, {name: &#39;Bob&#39;, city: &#39;LA&#39;}]<br>options = { row_sep: &quot;\r\n&quot;, col_sep: &#39;;&#39; }<br><br>SmarterCSV.generate(&#39;out.csv&#39;, options) do |csv|<br>  csv &lt;&lt; data<br>end</pre><p>Output:</p><pre>name;city\r\n<br>Alice;New York\r\n<br>Bob;LA\r\n</pre><p>This is especially useful when writing CSVs for Excel on Windows or systems that expect semicolon-separated data.</p><h3>Forcing Quoting on Everything</h3><p>Normally, only fields with problematic characters (commas, newlines, quotes) are quoted automatically. But you can force quoting on <strong>every</strong> header and data value:</p><pre>data = [{name: &#39;Alice&#39;, age: 30}, {name: &#39;Bob&#39;, age: 25}]<br><br>SmarterCSV.generate(&#39;out.csv&#39;, force_quotes: true) do |csv|<br>  csv &lt;&lt; data<br>end</pre><p>Output:</p><pre>&quot;name&quot;,&quot;age&quot;<br>&quot;Alice&quot;,&quot;30&quot;<br>&quot;Bob&quot;,&quot;25&quot;</pre><p>This can be helpful for consistency or when importing into systems that expect all values quoted.</p><h3>Advanced Control Features</h3><p>Similar to the header_converterwe saw earlier, with value_converters you get full control over how data values are converted into CSV fields. You can</p><ul><li>convert values for specific fields</li><li>convert values for all fields</li></ul><h3>Converting Values for Specific Fields</h3><p>With value_converters you can define lambdas for specific keys, which will convert the values for the output.</p><p>This maps the boolean value of :active to a corresponding emoji:</p><pre>data = [{ name: &#39;Alice&#39;, age: 42, active: true, balance: 234.235 },<br>        { name: &#39;Joe&#39;, age: 53, active: nil, balance: 150 }<br>       ]<br>options = { <br>  value_converters: {<br>    active: -&gt;(v) { !!v ? &#39;✅&#39; : &#39;❌&#39; },<br>    balance: -&gt;(v) { v.round(2) },<br>  }<br>}<br>SmarterCSV.generate(&#39;out.csv&#39;, options) do |csv|<br>  csv &lt;&lt; data<br>end</pre><p>Output:</p><pre>name,age,active,balance<br>Alice,42,✅,234.24<br>Joe,53,❌,150</pre><p>Note how Alice’s balance is rounded, but Joe’s is an integer. Looks like we need more control.</p><h3>Advanced Example</h3><p>Let’s take this a step further with a more advanced example and map the balance into a string prefixed by a dollar sign, and round float values to 2 digits. Finally we want to force-quote all strings in the data rows as well as in the header.</p><pre>data1 = { name: &#39;Alice&#39;, age: 42, active: true, balance: 234.235 }<br>data2 = { name: &#39;Joe&#39;, age: 53, active: nil, balance: 150 }<br><br>options = {<br>  value_converters: {<br>    active: -&gt;(v) { v ? &#39;✅&#39; : &#39;❌&#39; },<br>    balance: -&gt;(v) do<br>      case v<br>      when Float<br>        &#39;$%.2f&#39; % v.round(2)<br>      when Integer<br>        &quot;$#{v}.00&quot;<br>      else<br>        v.to_s<br>      end<br>    end,<br>    _all: -&gt;(_k, v) { v.is_a?(String) ? &quot;\&quot;#{v}\&quot;&quot; : v } # only quote string fields<br>  },<br>  header_converter: -&gt;(header) { header.upcase }, <br>  quote_headers: true, # manually quote headers<br>  disable_auto_quoting: true, # ⚠️ Important: turn off auto-quoting because we&#39;re manually quoting<br>}<br><br>writer = SmarterCSV::Writer.new(&#39;out.csv&#39;, options)<br>writer &lt;&lt; data1<br>writer &lt;&lt; data2<br>writer.finalize</pre><p>To recap, we are using two new value_converters:</p><ul><li>converting the :balance based on the type of the value into a rounded, formatted string with a dollar sign.</li><li>quoting all string fields</li></ul><p>as well as a header_converter that transforms all headers to upper case, and finally we are manually quoting all header fields.</p><p>This gives us this output:</p><pre>&quot;NAME&quot;,&quot;AGE&quot;,&quot;ACTIVE&quot;,&quot;BALANCE&quot;<br>&quot;Alice&quot;,42,&quot;✅&quot;,&quot;$234.24&quot;<br>&quot;Joe&quot;,53,&quot;❌&quot;,&quot;$150.00&quot;</pre><p>Note how the numerical values for :age are not quoted, and how the values for :balance are prefixed with a dollar sign and have 2 decimals.</p><h3><strong>SmarterCSV: Writing That Just Works</strong></h3><p><a href="https://github.com/tilo/smarter_csv">SmarterCSV</a>’s new writing capabilities bring the same flexibility and robustness to exporting data as it already does to reading it.</p><p>Whether you need a quick one-off CSV export or full control over headers, quoting, and data formatting, <a href="https://github.com/tilo/smarter_csv">SmarterCSV</a> can save you time and hassle. It handles mixed data structures gracefully, escapes problematic values, and grows with your data — making it a powerful, no-fuss solution for real-world CSV workflows in Ruby.</p><p>Check it out on GitHub: <a href="https://github.com/tilo/smarter_csv">https://github.com/tilo/smarter_csv</a> ⭐</p><p><strong>Read Next: Dive deeper into </strong><a href="https://medium.com/@tilo-sloboda/parsing-csv-files-in-ruby-with-smartercsv-6ce66fb6cf38"><strong>reading CSV files with SmarterCSV</strong></a><strong>.</strong>💡</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26136d47ad0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Safely Delete Old Ruby Code with deprecate_soft]]></title>
            <link>https://tilo-sloboda.medium.com/safely-delete-old-code-with-deprecate-soft-89e819b41d52?source=rss-e3182782ff7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/89e819b41d52</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[technical-debt]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Tilo Sloboda]]></dc:creator>
            <pubDate>Tue, 25 Mar 2025 00:47:28 GMT</pubDate>
            <atom:updated>2025-03-25T17:18:02.584Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2p-HVbCgLfnLl2-x9hDJ3A.jpeg" /></figure><h3>Is it safe to remove?</h3><p>If you’ve ever had to refactor or remove old code in a large production system, you know how hard it is to answer a simple question: “Is this method still being used?”</p><p>When you’re operating in a massive codebase — dozens of teams, hundreds of engineers, thousands of deployments — you can’t just delete an old method and “hope for the best.”</p><p>Some try to warn developers by printing deprecation warnings to logs. Others try to raise errors to force deprecation enforcement after a set time period. But none of that is helpful in production, where logs are often ignored, and user-impacting exceptions should only be used for real errors.</p><p>We needed something better.</p><h3>Introducing deprecate_soft</h3><p><a href="https://github.com/tilo/deprecate_soft">deprecate_soft</a> is a lightweight Ruby gem designed to help you track deprecated method usage in production without affecting behavior or user experience. You mark a method as deprecated, and the gem wraps it with tracking hooks which you can customize— allowing you to increment counters, emit metrics, or just log structured usage data before you remove it — <strong>answering the two most important questions</strong>:</p><ul><li><strong>Is it safe to remove?</strong></li><li><strong>Where is it still being used?</strong></li></ul><h3>Why It Works</h3><p>Because <a href="https://github.com/tilo/deprecate_soft">deprecate_soft</a> works with custom hooks, you can plug it into your observability stack — Redis, StatsD, DataDog, Prometheus, even plain old logs. It’s safe to run in production, has zero impact on the caller, and gives you metrics to support your cleanup efforts.</p><p>This mechanism has been proven in large-scale production systems to safely clean up legacy code — and this gem reimagines that functionality to help you clean up your code with confidence.</p><p>Tip: It is best to ceate a dedicated DataDog dashboard to track your deprecations and your code deletion progress.</p><h3>🧪 Basic Example: is it safe to remove?</h3><pre>class MyService<br>  include DeprecateSoft<br><br>  def do_something_legacy(arg)<br>    # original logic<br>  end<br><br>  deprecate_soft :do_something_legacy, &quot;Use #do_something_modern instead&quot;<br>end</pre><p>This wraps the method with logic that calls a globally configured before_hook and after_hook. You configure the behavior once for your entire app, like so:</p><pre># config/initializers/deprecate_soft.rb<br><br>require &quot;deprecate_soft&quot;<br>require &#39;datadog/statsd&#39;<br><br>statsd = Datadog::Statsd.new<br><br>DeprecateSoft.configure do |config|<br>  config.before_hook = lambda do |method, message, args:|<br>    # Example: increment a Redis counter<br>    redis.incr(&quot;deprecate_soft:#{method}&quot;)<br>    <br>    # Example: send a metric<br>    statsd.increment(&quot;deprecate_soft.#{method.tr(&#39;#&#39;, &#39;.&#39;)}&quot;)<br><br>    # Or just log it<br>    Rails.logger.warn &quot;DEPRECATED: #{method} — #{message}&quot;<br>  end<br>end</pre><p>Once usage of the deprecated method reaches zero, you can safely delete it.</p><h3>🧪🧪🧪 Advanced Example : where is it being used?</h3><p>Tracking where a deprecated method is being called from can be incredibly useful in large databases. You can achieve this by capturing the caller’s locations and recording that info in your before_hook.</p><p>Here’s a complete example of how to configure <a href="https://github.com/tilo/deprecate_soft">deprecate_soft</a> to:</p><p>✅ Track <strong>if method is used</strong><br> ✅ Track <strong>who is calling it </strong>(file + line number)<br> ✅ Maintain <strong>per-caller counters</strong> in Redis</p><pre># config/initializers/deprecate_soft.rb<br><br>require &quot;deprecate_soft&quot;<br>require &#39;redis&#39;<br><br># Configure your redis client instance<br>redis = Redis.new(url: ENV.fetch(&quot;REDIS_URL&quot;, &quot;redis://localhost:6379/0&quot;))<br><br>DeprecateSoft.configure do |config|<br>  config.before_hook = lambda do |method, message, args:|<br>    # Get the direct caller of the deprecated method<br>    caller_info = caller_locations(1, 1).first<br><br>    caller_key = if caller_info<br>      &quot;#{caller_info.path}:#{caller_info.lineno}&quot;<br>    else<br>      &quot;unknown&quot;<br>    end<br><br>    # Track a global usage counter<br>    redis.incr(&quot;deprecate_soft:#{method}&quot;)<br><br>    # Track usage by caller location<br>    redis.incr(&quot;deprecate_soft:#{method}:caller:#{caller_key}&quot;)<br><br>    # Log the usage by caller location<br>    Rails.logger.info(&quot;Deprecated #{method} called from #{caller_key}&quot;)<br>  end<br>end</pre><h3>Example output in Redis</h3><p>If Klass#legacy_method is called from app/services/foo.rb:42:</p><ul><li>Klass#legacy_method → 7</li><li>Klass#legacy_method:caller:app/services/foo.rb:42 → 3</li><li>Klass#legacy_method:caller:app/jobs/cleanup_job.rb:88 → 4</li></ul><p>Now you not only know <strong>that</strong> the method is still used — you know <strong>where from</strong>, and how often — so you can fix your code.</p><h3>Why Not Just Use Other Deprecations?</h3><p>Ruby and Rails already have built-in deprecation mechanisms — but they serve a different purpose: helping you migrate between framework versions. They’re meant for development environments, where you can respond to deprecation warnings and update your code before migrating to a new version.</p><p>But these tools are <strong>not observability tools for production</strong>.</p><p>In production systems:</p><ul><li>⚠️ <strong>Log messages are filtered</strong> — warnings or info-level logs are often dropped entirely.</li><li>🌊 <strong>Even if they make it to the logs, they’re drowned out</strong> by the sheer volume of noise.</li><li>🧑‍💻 <strong>No one reads the logs</strong> — and even if they do, it’s usually too late — logs are truncated.</li><li>💥 <strong>Throwing errors in deprecated methods breaks real user traffic</strong>, unnecessarily, and with no graceful fallback.</li></ul><p><a href="https://github.com/tilo/deprecate_soft">deprecate_soft</a> is built for production and gives you <strong>real, measurable signals</strong> you can track safely and continuously using Redis, DataDog, StatsD, or whatever tooling your team already relies on.</p><p>Want to verify that a method hasn’t been called in 30 days before deleting it? Now you can!</p><p><strong>No guessing. No hoping. No breakages.</strong></p><h3>Get Started</h3><p>Add the gem to your Gemfile:</p><pre>gem “deprecate_soft”</pre><p>Track usage. After a week or a month, verify it’s no longer called. Delete with confidence.</p><h3>When You Need to Be Sure</h3><p>Production systems deserve production-grade tooling. If you’re serious about keeping your codebase clean <strong>without breaking things</strong>, <a href="https://github.com/tilo/deprecate_soft">deprecate_soft</a> is the simplest way to get the job done safely.</p><p>Check it out on GitHub: <a href="https://github.com/tilo/deprecate_soft">https://github.com/tilo/deprecate_soft</a> ⭐</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89e819b41d52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Announcing SmarterCSV 1.13.0]]></title>
            <link>https://tilo-sloboda.medium.com/announcing-smartercsv-1-13-0-3aecf1e745af?source=rss-e3182782ff7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3aecf1e745af</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[rubygems]]></category>
            <category><![CDATA[csv]]></category>
            <category><![CDATA[data-processing]]></category>
            <dc:creator><![CDATA[Tilo Sloboda]]></dc:creator>
            <pubDate>Thu, 07 Nov 2024 04:53:02 GMT</pubDate>
            <atom:updated>2024-11-07T15:38:13.636Z</atom:updated>
            <content:encoded><![CDATA[<h4>Enhanced Robustness and Data Integrity in Ruby CSV Processing</h4><p>The popular <a href="https://github.com/tilo/smarter_csv">Ruby gem SmarterCSV <strong>1.13.0</strong></a><strong> </strong>was just released. This release focuses on improving robustness and reducing the risk of data loss, making CSV processing more reliable than ever. If you’re new to SmarterCSV or want to learn more about how to use this gem, check out this detailed guide: <a href="https://tilo-sloboda.medium.com/parsing-csv-files-in-ruby-with-smartercsv-6ce66fb6cf38">Parsing CSV Files in Ruby with SmarterCSV</a>.</p><h3>Changes in Default Behavior</h3><p>Version 1.13.0 introduces some <a href="https://github.com/tilo/smarter_csv/blob/main/CHANGELOG.md#1130-2024-11-06--potentially-breaking-">changes that may affect existing codebases</a>. Here’s what you need to know:</p><p><strong>1. Auto-Detection of Extra Columns</strong></p><ul><li><strong>What’s New:</strong> SmarterCSV now automatically detects extra columns in your CSV data, generating additional headers like :column_7, :column_8, etc.</li><li><strong>Benefit:</strong> This bug fix ensures that no data is silently ignored when a row contains more columns than the header specifies.</li><li><strong>Note:</strong> If you prefer the previous behavior, and want strict adherence to the header columns, you can set the option :strict to true to raise a SmarterCSV::MalformedCSV exception when extra columns are detected.</li><li><strong>Related Issues:</strong> <a href="https://github.com/tilo/smarter_csv/issues/284">#284</a></li></ul><p>2.<strong> Changes to </strong><strong>user_provided_headers Behavior</strong></p><ul><li><strong>What’s Changed:</strong> Setting user_provided_headers now implies headers_in_file: false.</li><li><strong>Benefit:</strong> This safer default behavior prevents accidental data loss by ensuring that the first line of data is not mistakenly treated as headers.</li><li><strong>Implication:</strong> If your CSV file includes headers but you are overriding them with user_provided_headers, you should explicitly set headers_in_file: true to avoid processing the actual headers as data.</li><li><strong>Related Issue:</strong> <a href="https://github.com/tilo/smarter_csv/issues/282">#282</a></li></ul><p><strong>3. Improved Handling of Unbalanced Quotes</strong></p><ul><li><strong>What’s New:</strong> The gem now raises a SmarterCSV::MalformedCSV exception when it encounters unbalanced quote_char in the input data.</li><li><strong>Benefit:</strong> This prevents potential EOF errors, data corruption or unexpected behavior due to malformed CSV entries.</li><li><strong>Related Issues:</strong> <a href="https://github.com/tilo/smarter_csv/issues/288">#288</a> and <a href="https://github.com/tilo/smarter_csv/issues/283">#283</a></li></ul><p><strong>4. Handling Numeric Columns with Leading Zeroes</strong></p><ul><li><strong>What’s New:</strong> Better documentation of how this feature can prevent automatic conversion of numeric columns that contain leading zeroes (e.g., ZIP codes) to integers. This was implemented in 1.10, but not well documented.</li><li><strong>How To:</strong> Use convert_values_to_numeric: { except: [:zip] } in your options to retain the original string format.</li><li><strong>Benefit:</strong> This ensures data like ZIP codes are accurately preserved without losing essential leading zeroes.</li><li><strong>Related Issue:</strong> <a href="https://github.com/tilo/smarter_csv/issues/151">#151</a></li></ul><p><strong>Why This Matters</strong></p><p>These updates significantly enhance the reliability of CSV data processing in Ruby applications. By addressing potential pitfalls like unbalanced quotes and extra columns, SmarterCSV 1.13.0 helps developers avoid subtle bugs and data inconsistencies.</p><p><strong>Action Steps</strong></p><ul><li><strong>Review the Changes:</strong> Since this release includes potentially breaking changes, it’s crucial to review the changelog and test your existing codebase before upgrading.</li><li><strong>Update Your Code:</strong> Make necessary adjustments, especially if you use user_provided_headers or rely on the gem&#39;s previous handling of extra columns.</li><li><strong>Stay Informed:</strong> Keep an eye on the <a href="https://github.com/tilo/smarter_csv">GitHub repository</a> for any further updates or discussions.</li></ul><p><strong>Get Involved</strong></p><p>SmarterCSV thrives on community contributions. If you encounter issues or have ideas for improvements, don’t hesitate to <a href="https://github.com/tilo/smarter_csv/issues">open an issue</a> or submit a pull request.</p><p>Upgrade to SmarterCSV 1.13.0 today to take advantage of these important enhancements. For more on how to effectively use SmarterCSV in your Ruby projects, read our guide: <a href="https://tilo-sloboda.medium.com/parsing-csv-files-in-ruby-with-smartercsv-6ce66fb6cf38">Parsing CSV Files in Ruby with SmarterCSV</a>. Happy coding! ✨</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3aecf1e745af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parsing CSV Files in Ruby with SmarterCSV]]></title>
            <link>https://tilo-sloboda.medium.com/parsing-csv-files-in-ruby-with-smartercsv-6ce66fb6cf38?source=rss-e3182782ff7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ce66fb6cf38</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[data-ingestion]]></category>
            <category><![CDATA[csv]]></category>
            <dc:creator><![CDATA[Tilo Sloboda]]></dc:creator>
            <pubDate>Mon, 08 Jul 2024 13:06:38 GMT</pubDate>
            <atom:updated>2025-04-10T07:51:03.713Z</atom:updated>
            <content:encoded><![CDATA[<h4>Tame real-world CSVs with smart, resilient defaults</h4><p>Working with CSV (Comma Separated Values) files is a very common task, and SmarterCSV is the easiest and most powerful tool for the job. This article gives an overview of its capabilities, and contrasts it against Ruby’s “csv” library.</p><h4>Introduction</h4><p>CSV files are a common data exchange format. They are simple text files with rows of data, where each row has columns that are typically separated by commas. This article will show you how to use the SmarterCSV Ruby gem to easily read and process CSV files efficiently.</p><h4>Intelligent Defaults</h4><p>While Ruby’s “csv” library has a bare-bones feel to it, returning an array for each row, SmarterCSV uses intelligent default settings, and a standardized pre-processing of input data, to massage the data into a more usable format, and it returns an easy-to-use Ruby hash for each row. This eliminates a lot of the manually post-processing that would be needed otherwise. These smart defaults help you get more consistent data quality when importing CSV data over which you typically have little or no quality control.</p><p>Instead of just spitting-out raw data in array format, SmarterCSV massages the data into a usable form and returns a Ruby hash. Here’s an example of a CSV file with non-standard column separators, and emojis:</p><pre>$ cat /tmp/my.csv<br>&quot;First Name &quot;|&quot; Last   Name&quot;|Emoji | pets<br>José  |  Corazón| ❤️ | 2<br>   Jürgen|Müller  |😐 | 1<br>Michael  |May|  😞 |0</pre><p>SmarterCSV is like CSV processing on auto-pilot:</p><pre>require &#39;smarter_csv&#39;<br>filename = &#39;/tmp/my.csv&#39;<br><br>data = SmarterCSV.process(filename)<br><br>=&gt; [<br>  {:first_name=&gt;&quot;José&quot;, :last_name=&gt;&quot;Corazón&quot;, :emoji=&gt;&quot;❤️&quot;, :pets=&gt;2}, <br>  {:first_name=&gt;&quot;Jürgen&quot;, :last_name=&gt;&quot;Müller&quot;, :emoji=&gt;&quot;😐&quot;, :pets=&gt;1}, <br>  {:first_name=&gt;&quot;Michael&quot;, :last_name=&gt;&quot;May&quot;, :emoji=&gt;&quot;😞&quot;, :pets=&gt;0}<br>]</pre><p>Using its default setting of col_sep: :auto, and row_sep: :auto, SmarterCSV automatically figures out that the line endings, and the column separator|. Emojis and UTF-8 characters are handled properly by default. It automatically trimmed off the extra spaces in the headers and the data rows, and transformed the headers into Ruby symbols to be used as keys in the individual data hashes. Numerical values are converted automatically into the appropriate type. You can also add your own custom <a href="https://github.com/tilo/smarter_csv/blob/main/docs/value_converters.md">value converters</a>.</p><p>This automatic detection of the most common CSV formats helps making your code more resilient against variations in the input data over which you have no control — e.g. when users upload CSV files to your service.</p><p>And did you notice the output format?</p><h4>Ruby Hashes for the Win!</h4><p>Perhaps the most important design choice for SmarterCSV is to represent the rows of input data as simple Ruby hashes, using symbols as keys.</p><p>This allows very easy processing of the data, no matter if you need to pass it on to ActiveRecord, S3, or Sidekiq — SmarterCSV makes it a breeze to integrate with these use cases.</p><h4>Memory Consumption</h4><p>Reading large CSV files can consume a lot of memory if loaded entirely.<br>SmarterCSV handles this efficiently by processing files line-by-line. For very large files and for feeding parallel processing, it can also process the input data in chunks. Here’s how to process very large files in chunks:</p><pre>require &#39;smarter_csv&#39;<br><br>SmarterCSV.process(&#39;your_file.csv&#39;, { chunk_size: 1000 }) do |array-of-hashes|<br>  # do bulk-inserts, -upserts, or pass chunks of data to a Sidekiq worker<br>  MyModel.insert_all(array-of-hashes)<br>end</pre><h4>Not Only File Input</h4><p>SmarterCSV is not limited to processing input files, but can also process any input from any IO-like object that responds to readline—including strings, or open file handles.</p><pre>csv_string = &quot;name,age,city\nJohn,30,New York\nJane,25,San Francisco&quot;<br><br>SmarterCSV.process(StringIO.new(csv_string)) do |row_hash|<br>  array.each do |row|<br>    # Process each hash representing a row of data<br>  end<br>end</pre><p>Using StringIO, you can easily feed string data to SmarterCSV, but be careful to not read the complete contents into memory all at once. It is best to chunk your data, and release already processed chunks.</p><h4>Importing CSV Data into Rails Models</h4><p>Importing data from CSV into Rails models is straightforward with SmarterCSV. Here’s an example of how you can import company data, assuming that each row has a unique tax-id:</p><pre>class Company &lt; ApplicationRecord<br>end<br><br>file_path = &#39;path/to/companies.csv&#39;<br><br>SmarterCSV.process(file_path, { chunk_size: 1000 }) do |chunk|<br>  Company.upsert_all(chunk, unique_by: :tax_id)<br>end</pre><h4>Importing CSV Data with Sidekiq</h4><p>When passing large amounts of input data to Sidekiq, a good pattern is to use an enqueuer worker that accepts chunks of data, which then kicks-off individual workers for each row of data. This way, you can enqueue and hand-off the work fast, and still track the individual progress for each individual worker, representing one row of data.</p><pre>file_path = &#39;path/to/upload.csv&#39;<br><br>SmarterCSV.process(file_path, { chunk_size: 1000 }) do |array-of-hashes|<br>  MySidekiqEnqueuer.perform_async(array-of-hashes)<br>end</pre><pre>class MySidekiqEnqueuer<br>  include Sidekiq::Worker<br><br>  def perform(chunk)<br>    chunk.each do |record|<br>      # kick-off individual workers for each row<br>      MySidekiqWorker.perform_async(record)<br>    end<br>  end<br>end</pre><h4>Example: Importing Course Data</h4><p>When working with a Rails application, you might need to import data into your models. For instance, let’s consider a scenario where you have a list of courses in CSV format that you want to import into your Rails application as Course models.</p><p>First, ensure that you have a Course model in your Rails application. It might look something like this:</p><pre>class Course &lt; ApplicationRecord<br> # your code<br>end</pre><p>Normally you’d need to create a parser that reads the CSV file, normalizes the input data, and then creates Course records. You can do this in a Rake task, a service object, or directly in a controller action, depending on your needs and the application&#39;s overall architecture.</p><p>With SmarterCSV the rake task becomes trivial:</p><pre># Place in lib/tasks/<br>require &quot;smarter_csv&quot;<br><br>namespace :import do<br>  desc &quot;Import courses from a CSV file&quot;<br>  task courses: :environment do<br>    SmarterCSV.process((&quot;your_file.csv&quot;) do |row_hash|<br>      # { name: &quot;CS 101&quot;, description: &quot;CS basics&quot;, instructor: &quot;John Smith&quot; }<br>      Course.create!(row_hash)<br>    end<br>    # this could be even faster using bulk-inserting (see chunked example)<br>  end<br>end</pre><p>This rake task assumes you have the file you’d like to import in directory/your_file.csv, and it contains Name, Description, and Instructor headers. It will then create and persist a Course object with the data in those columns.</p><p>In contrast to a solution using the csv gem, SmarterCSV already eliminates a lot of the possible data issues.</p><h4>Example: Exporting Course Data to CSV</h4><p>SmarterCSV can also be used to create CSV files. e.g. it can provide an export functionality — exporting data from your application’s database into a CSV file.</p><p>For simplicity, let’s assume you’re exporting the data from a controller action.</p><p>Here’s a controller export action that creates a CSV file from the Course model, and only exports the given attributes:</p><pre>require &quot;smarter_csv&quot;<br>require &quot;fileio&quot;<br><br>class CoursesController &lt; ApplicationController<br>  CSV_OPTIONS = { <br>    map_headers: {<br>      name: &#39;Course&#39;, <br>      description: &#39;Content Summary&#39;, <br>      instructor: &#39;Professor&#39;,<br>    }<br>  }.freeze<br><br>  def export<br>    file_path = &quot;/tmp/courses-#{Date.today}.csv&quot;<br><br>    # create the CSV temp file<br>    SmarterCSV.generate(file_path, CSV_OPTIONS) do |csv_writer|<br>      Course.find_in_batches(batch_size: 100) do |batch|<br>        csv_writer &lt;&lt; batch<br>      end<br>    end  <br><br>    # send it!<br>    send_file file_path, filename: File.basename(file_path)<br><br>  ensure<br>    # Ensure the temp file is deleted after sending<br>    File.delete(file_path) if File.exist?(file_path)<br>  end<br>end</pre><p>SmarterCSV.generate is a convenience method around creating a SmarterCSV::Writer instance, which can take one or many calls of the &lt;&lt; operator to append data to a file. Using map_headers is one way to define the CSV headers for each attribute. We get this output:</p><pre>&gt; cat /tmp/courses-2024-07-04.csv<br>Course,Content Summary,Professor<br>15-213,Introduction to Computer Systems,Brian Railing<br>15-852,Parallel and Concurrent Algorithms,Walter Tichy</pre><p>This only scratches the surface of CSV writing. Read more about <a href="https://tilo-sloboda.medium.com/csv-writing-with-smartercsv-26136d47ad0c">writing CSV With SmarterCSV</a>.</p><h4>Comparison with Ruby’s Standard CSV Library</h4><p>Ruby’s built-in CSV library offers basic parsing functionality and represents rows as arrays. SmarterCSV takes things further.</p><p>It uses Ruby <strong>hashes as the default row format </strong>— a more idiomatic choice for most Ruby and Rails applications.</p><p>SmarterCSV is optimized for performance and can process <strong>large files efficiently</strong>, even in parallel. By working in <strong>chunks</strong>, it significantly reduces memory usage.</p><p>It also ships with <strong>smart defaults</strong> that automatically clean and normalize real-world input. It handles file encodings gracefully and supports <strong>custom data transformations</strong> out of the box.</p><p>These features make SmarterCSV a better fit for real-world CSV processing — especially when you’re dealing with<strong> large datasets</strong>, <strong>complex pipelines</strong>, or <strong>unpredictable real-world data</strong> like user-uploaded files.</p><h4>Conclusion</h4><p>SmarterCSV is a powerful and efficient gem for handling CSV files in Ruby. With features like chunk processing, custom data transformations, intelligent default settings, and easy integration with Rails, it is an excellent choice for managing CSV data. Its ease-of-use, data-normalization, and flexibility make it superior to the Ruby “csv” library, especially when you have large datasets and want to do batch processing.</p><p>SmarterCSV handles real-world CSV data gracefully — whether you’re importing messy files, chunking large datasets, or piping in IO streams. Its defaults work out of the box, and its flexibility gives you full control when you need it.</p><p>Check out SmarterCSV on GitHub: <a href="https://github.com/tilo/smarter_csv">https://github.com/tilo/smarter_csv</a> ⭐</p><p><strong>Next up</strong>: Learn how to <a href="https://medium.com/@tilo-sloboda/csv-writing-with-smartercsv-26136d47ad0c"><strong>write CSV files with SmarterCSV </strong></a>— with just as much flexibility and control. 💡</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ce66fb6cf38" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HexaPDF : the cool kid on the block!]]></title>
            <link>https://tilo-sloboda.medium.com/hexapdf-the-cool-kid-on-the-block-1b8452993866?source=rss-e3182782ff7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b8452993866</guid>
            <category><![CDATA[pdfboo]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[pdf]]></category>
            <dc:creator><![CDATA[Tilo Sloboda]]></dc:creator>
            <pubDate>Thu, 18 Jan 2024 17:26:33 GMT</pubDate>
            <atom:updated>2024-02-19T21:01:18.372Z</atom:updated>
            <content:encoded><![CDATA[<h3>HexaPDF: the cool kid on the block!</h3><h4>Using a JVM-based tool like pdftk to process PDFs in Ruby?</h4><p>There are some Ruby gems for PDF generation, like Prawn, but previously there were no great options for filling out PDF forms. In the past you needed to fall-back to JVM-based tools like pdftk for doing this.</p><p><a href="https://github.com/gettalong/hexapdf">HexaPDF</a> is a native Ruby gem that is greatly improving PDF creation and manipulation for Ruby developers, and simplifying the dependencies of your project.</p><p>HexaPDF offers a wider range of features, including the manipulation and merging of existing PDFs, extracting content, optimizing files, and filling out forms. Prawn, on the other hand, primarily focuses on PDF generation from scratch.</p><p>HexaPDF also supports advanced features like embedding various image formats, font subsetting, PDF forms, digital signatures, and encryption. Prawn, while capable of embedding images and fonts, lacks the advanced features like forms, signatures, and encryption.</p><p>Explore more about HexaPDF on <a href="https://github.com/gettalong/hexapdf">GitHub</a> and on their <a href="https://hexapdf.gettalong.org/documentation/getting-started/index.html">Wiki</a>. There is a section about the <a href="https://github.com/gettalong/hexapdf#difference-to-prawn">differences to Prawn</a>, as well as a <a href="https://hexapdf.gettalong.org/documentation/getting-started/index.html">migration guide</a>.</p><h3>Example</h3><p>When it comes to filling-out forms, one of the key features of HexaPDF is its ability to handle various types of PDF forms, such as text fields, button fields (like checkboxes), and choice fields (like dropdowns). This versatility makes it an invaluable tool for developers working on projects that require complex PDF manipulation.</p><p>The following sample program demonstrates <a href="https://github.com/gettalong/hexapdf">HexaPDF</a>’s ease of use and functionality:</p><pre>require &#39;hexapdf&#39;<br><br>input_pdf = &#39;/tmp/f1099msc.pdf&#39;<br>output_pdf = &#39;/tmp/output.pdf&#39;<br><br>doc = HexaPDF::Document.open(input_pdf)<br>i = 0<br>if doc.acro_form<br>  doc.acro_form.each_field do |field|<br>    begin<br>      case field.field_type <br>      when :Tx  # Text field<br>        field.field_value = field.field_name<br>      when :Btn  # Button field (like checkboxes)<br>        # Handle button-specific logic here<br>      when :Ch  # Choice field (like dropdowns)<br>        # Handle choice-specific logic here<br>      else<br>        puts &quot;Unsupported field type: #{field[:FT]}&quot;<br>      end<br>    rescue <br>      field.field_value = i.to_s<br>      puts &quot;Field size limitation for field: #{field.field_name}, using: #{i}&quot;<br>      i += 1<br>    end<br>  end<br>  doc.write(output_pdf)<br>else<br>  puts &quot;No form fields found in the PDF.&quot;<br>end</pre><p>In this example, <a href="https://github.com/gettalong/hexapdf">HexaPDF</a> is used to open a 1099-misc form, iterate through its form fields, and modify them based on their type. It then fills out the form with the field names that are used internally in the PDF.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PTPtMS-W5LAWvnooimI0bQ.png" /></figure><h3>Conclusion</h3><p>HexaPDF is a powerful tool that has more functionality than Prawn, and being a native Ruby gem, you no longer have to deal with JVM-based tools when having to fill out PDF documents. It simplifies your code and your project dependencies.<br> <br>Explore more about HexaPDF on <a href="https://github.com/gettalong/hexapdf">GitHub</a> and on their <a href="https://hexapdf.gettalong.org/documentation/getting-started/index.html">Wiki</a>.</p><p>enjoy! 🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b8452993866" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Set Up Emoji Shortcuts on ZSA Keyboards for macOS ❤️]]></title>
            <link>https://tilo-sloboda.medium.com/how-to-set-up-emoji-shortcuts-on-zsa-keyboards-for-macos-%EF%B8%8F-631b5f12ad7a?source=rss-e3182782ff7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/631b5f12ad7a</guid>
            <category><![CDATA[moonlander]]></category>
            <category><![CDATA[voyager]]></category>
            <category><![CDATA[keyboard-layout]]></category>
            <category><![CDATA[emoji-keyboard]]></category>
            <category><![CDATA[ergodox-ez]]></category>
            <dc:creator><![CDATA[Tilo Sloboda]]></dc:creator>
            <pubDate>Sun, 05 Nov 2023 21:13:18 GMT</pubDate>
            <atom:updated>2023-11-08T17:27:01.534Z</atom:updated>
            <content:encoded><![CDATA[<p>Emojis are an integral part of daily life, adding emotion and clarity to our messages. For ZSA keyboard users on macOS, creating emoji shortcuts can streamline your workflow and inject fun into your daily typing tasks. This guide will walk you through setting up emoji shortcuts using three popular macOS tools: <a href="https://folivora.ai/">BetterTouchTool</a>, <a href="https://textexpander.com/">TextExpander</a>, and <a href="https://www.keyboardmaestro.com/main/">Keyboard Maestro</a>.</p><figure><img alt="Example for Emoji Layout" src="https://cdn-images-1.medium.com/max/565/1*ix6tATUGf1eqeoB5O01clA.png" /><figcaption>Example for Emoji Layer</figcaption></figure><h3>Customizing your ZSA Keyboard: The Power of Flexibility</h3><p>ZSA keyboards like the <a href="https://www.zsa.io/voyager/">Voyager</a>, <a href="https://www.zsa.io/moonlander">Moonlander</a>, and <a href="https://ergodox-ez.com/">ErgoDox EZ</a> are celebrated for their unparalleled customizability and ergonomic benefits. To personalize your ZSA keyboard, use the online <a href="https://configure.zsa.io/">Oryx Configurator</a> to select and modify layouts, reassign key functions, and create multiple layers for different uses, such as a dedicated emoji layer. After customizing, simply flash your new layout onto the keyboard.</p><p>The flexibility of ZSA keyboards lies in their <a href="https://blog.zsa.io/tags/oryx/">fully programmable keys</a>, allowing for <a href="https://blog.zsa.io/macros-vs-shortcuts/">complex macros</a> and <a href="https://blog.zsa.io/compact-layouts/">dual-function assignments</a>. With support for multiple layers, you can switch between entire sets of keybindings effortlessly.</p><h3>Simple Three-Step Process:</h3><ol><li><strong>Plan your Emoji Layout</strong><br>Decide on a consistent and memorable prefix, e.g. ~ or ;, for your emoji shortcuts, and name each emoji with a short code, such as ~smi for 🙂, ~thufor 👍, ~thdfor 👎, ~hrtfor ❤️, etc.<br>Keep in mind that macros on ZSA keyboards are limited to 5 characters.</li></ol><figure><img alt="Emoji Shortcuts" src="https://cdn-images-1.medium.com/max/121/1*wOzHQ2mQ59aFVCa6o9UMDA.png" /><figcaption>Example for Emoji Shortcut</figcaption></figure><ol><li><strong>Configure the Layer in </strong><a href="https://configure.zsa.io/"><strong>Oryx Configurator</strong></a><br>Create a new layer you want to use for emojis, and assign a key to activate your emoji layer, and create macros to emit your shortcuts.</li><li><strong>Translate the Shortcuts into Unicode</strong><br>Using a third-party expansion software, translate the shortcuts into the actual Unicode for the emoji.</li></ol><h3><strong>TL;DR:</strong> <strong>How it works</strong></h3><p>When you press the key, the ZSA keyboard will emit the shortcut, e.g. ~hrt , and the third-party software will replace it with the Unicode for the emoji ❤️. This has the advantage that it works in all MacOS apps and text input fields.</p><p>You might also want to checkout this <a href="https://configure.zsa.io/moonlander/layouts/yEZKl/latest/8">Moonlander layout with an emoji layer</a>.</p><h3>Unlock the Power of Emojis on ZSA Keyboards: Macros to the Rescue</h3><p>In the Oryx Configurator, create a new layer, and assign a key to activate yor emoji layer, e.g. holding down “E” to activate the emoji layer.</p><p>In your new emoji layer, click on a key you want to assign, then click on “when tapped”, and in the pop-up, select “Macro”. Now assign each character of the shortcut to the macro, e.g. ~, S, M, I. When done you can label the key with the actual emoji 🙂. Rinse, repeat!</p><p>I wish ZSA would make entering the macro easier, e.g. allow the user to type the character sequence until a button is pressed, but for now you have to enter the characters one by one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*w_4J2jimEE_8XiLmF55ziQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*zDie2fdRGXBbD2PQcRbM6Q.png" /><figcaption>Configuring the ZSA key to emit a shortcut for an emoji</figcaption></figure><p>Now all we need to do is to configure a third-party tool to translate the shortcut into the Unicode that represents the emoji.</p><h3><strong>Below, find Details on the Configuration for:</strong></h3><ol><li><strong>TextExpander</strong></li><li><strong>Keyboard Maestro</strong></li><li><strong>BetterTouchTool</strong></li></ol><h3>Streamline Your Typing with TextExpander</h3><p>TextExpander excels in creating quick and efficient text shortcuts. Follow these steps to expand snippets into emojis:</p><h3>Getting Started</h3><ol><li><a href="https://textexpander.com/"><strong>Download and install TextExpander</strong></a><strong>: </strong>Open TextExpander from your Applications.</li><li><strong>Create a New Snippet</strong>: Click the “+” button to add a new text snippet.</li><li><strong>Define Your Abbreviation</strong>: Enter the abbreviation that will trigger the emoji, like ~lol</li><li><strong>Paste Your Emoji</strong>: In the content field, paste the 😆 emoji.</li><li><strong>Save and Implement</strong>: Save your snippet and start using it across your macOS applications.</li></ol><h3>Automate Emojis with Keyboard Maestro</h3><p>Keyboard Maestro provides a robust platform for automating virtually any task on your Mac, including typing emojis. Here’s how to set it up:</p><h3>Configuration Steps</h3><ol><li><a href="https://www.keyboardmaestro.com/main/"><strong>Download and Launch Keyboard Maestro</strong></a>: Open Keyboard Maestro from your Applications.</li><li><strong>Create a New Macro</strong>: Click the “New Macro” button and name it after the emoji.</li><li><strong>Set Your Trigger</strong>: Choose “Hot Key Trigger” and input your desired key sequence for the shortcut, e.g. ~lol.</li><li><strong>Define the Action</strong>: Select “Insert Text” and paste-in the 😆 emoji.</li><li><strong>Activate and Enjoy</strong>: Enable the macro and use it in any application on your Mac.</li></ol><h3>Unlock the Power of Emojis with BetterTouchTool</h3><p>BetterTouchTool is another potent application that can transform your ZSA keyboard into an emoji-typing powerhouse. Here’s how to map your shortcuts to the Unicode characters for the emojis:</p><h3>Step-by-Step Guide</h3><p><a href="https://folivora.ai/downloads"><strong>Download</strong></a><strong> and Open BetterTouchTool, then:</strong></p><p><strong>A) Navigate to Keyboard Section</strong>: Click on the “Keyboard” icon to start creating your shortcuts.</p><figure><img alt="Select “Keyboard” in BetterTouchTool menu" src="https://cdn-images-1.medium.com/max/603/1*mG-B6Ghi8c6ibDgQxsyt-g.png" /><figcaption>Select “Keyboard”</figcaption></figure><p><strong>B) Create a New Shortcut</strong>: Select “Add New Shortcut”, then select “Key Sequence”, and press “Record New Key Sequence”. You will see a pop-up.</p><figure><img alt="Select “Add New Shortcut or Key Sequence”" src="https://cdn-images-1.medium.com/max/836/1*gsnO8WLLoTN0rvbjk2RMzQ.png" /><figcaption>Three Steps to start recording the Key Sequence</figcaption></figure><p><strong>C) Input Your Key Sequence</strong>: Type the sequence, such as ~smi, in the input field. Stop recording, and save.</p><figure><img alt="Type the character sequence for the shortcut" src="https://cdn-images-1.medium.com/max/773/1*w8R7S7UFQs31x9ltJg51ZQ.png" /><figcaption>Type the character sequence for the shortcut</figcaption></figure><p>To emit the Unicode for the emoji, we attach an additional action:</p><figure><img alt="Attach additional action" src="https://cdn-images-1.medium.com/max/826/1*Dh-dP4i91cZdc1x6Xl5UvA.png" /><figcaption>Attach Additional Action</figcaption></figure><p>Then define a “Trigger Predefined Action” to emit a specific custom text:</p><figure><img alt="Trigger Predefined Action: Paste Custom Text" src="https://cdn-images-1.medium.com/max/831/1*rPSq2_dmWTiM6E4hxC2izw.png" /><figcaption>Trigger Predefined Action: Paste Custom Text</figcaption></figure><p>Finally, <strong>Assign the Emoji to emit: </strong>Choose “Paste / Type Custom Text” and insert the “😊” emoji, then hit “Save”.</p><figure><img alt="Paste the Emoji or Unicode as the Custom Text" src="https://cdn-images-1.medium.com/max/719/1*vp0_VwYr7DTiAuolX6SQIA.png" /><figcaption>Paste the Emoji or Unicode as the Custom Text</figcaption></figure><p>Now just rinse &amp; repeat for the other emoji shortcuts you defined. 🎉</p><h3>Conclusion</h3><p>Setting up emoji shortcuts on your ZSA keyboard can greatly enhance your typing experience on macOS. Whether you choose BetterTouchTool for its versatility, TextExpander for its text-snippet prowess, or Keyboard Maestro for its automation capabilities, you’re just a few steps away from making your digital communication more expressive and efficient.</p><p>cheers! 🎉✨</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=631b5f12ad7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sublime Text: Font Size per File]]></title>
            <link>https://tilo-sloboda.medium.com/sublime-text-font-size-per-file-f296d61136d2?source=rss-e3182782ff7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f296d61136d2</guid>
            <category><![CDATA[sublime]]></category>
            <category><![CDATA[plugins]]></category>
            <category><![CDATA[sublimetext]]></category>
            <category><![CDATA[font-size]]></category>
            <dc:creator><![CDATA[Tilo Sloboda]]></dc:creator>
            <pubDate>Wed, 18 Oct 2023 22:44:46 GMT</pubDate>
            <atom:updated>2024-04-03T17:25:31.776Z</atom:updated>
            <content:encoded><![CDATA[<p>By default, changing the font size in Sublime Text, changes the font size in all windows.</p><p>Sometimes you want more granular control, e.g. when sharing your screen on a conference call.</p><p>It is easy to create a custom Plugin, that lets you increase or decrease the font size of each individual file, and easily revert back to the default setting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*Xq-Gkcf7XAGhj8zSVR_ifg.jpeg" /></figure><h3>Custom Plugin</h3><ol><li>In the Sublime toolbar, go to “Tools” &gt; “Developers” &gt; “New Plugin…”<br>This opens a new file with a skeleton of a plugin.</li><li>Replace the file contents with this code:</li></ol><pre>import sublime<br>import sublime_plugin<br><br><br>class ChangeViewFontSizeCommand(sublime_plugin.TextCommand):<br>    def run(self, edit, by):<br>        settings = self.view.settings()<br>        settings.set(&quot;font_size&quot;, settings.get(&quot;font_size&quot;) + by)<br><br>class ResetLocalFontSizeCommand(sublime_plugin.TextCommand):<br>    def run(self, edit):<br>        self.view.settings().erase(&quot;font_size&quot;)</pre><p>Save this file as change_view_font_size.py</p><p>3. Copy the extension into the Sublime folder for User packages:</p><pre>cp change_view_font_size.py ~/Library/Application\ Support/Sublime\ Text/Packages/User/</pre><p>4. In the Sublime toolbar, go to “Settings…” &gt; “Key Bindings” and add these lines to your sublime-keymap file:</p><pre>[<br>  { &quot;keys&quot;: [&quot;command+shift+=&quot;], &quot;command&quot;: &quot;change_view_font_size&quot;, &quot;args&quot;: {&quot;by&quot;: 1} },<br>  { &quot;keys&quot;: [&quot;command+shift+-&quot;], &quot;command&quot;: &quot;change_view_font_size&quot;, &quot;args&quot;: {&quot;by&quot;: -1} },<br>  { &quot;keys&quot;: [&quot;command+shift+0&quot;], &quot;command&quot;: &quot;reset_local_font_size&quot; },<br>]</pre><h3>Changing Font Size of one File</h3><p>Now when you type ⌘ ⇧ = or ⌘ ⇧ -, the font size of the specific file you are in will increase or decrease accordingly.</p><p>You can reset the font size to the default by typing ⌘ ⇧ 0</p><p>enjoy! 😃</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f296d61136d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>