惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

宝玉的分享
宝玉的分享
博客园 - 【当耐特】
NISL@THU
NISL@THU
IT之家
IT之家
博客园 - 叶小钗
M
MIT News - Artificial intelligence
博客园_首页
Hugging Face - Blog
Hugging Face - Blog
量子位
The Register - Security
The Register - Security
爱范儿
爱范儿
酷 壳 – CoolShell
酷 壳 – CoolShell
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
S
Security Affairs
W
WeLiveSecurity
S
Security @ Cisco Blogs
Apple Machine Learning Research
Apple Machine Learning Research
V2EX - 技术
V2EX - 技术
The Last Watchdog
The Last Watchdog
Blog — PlanetScale
Blog — PlanetScale
美团技术团队
J
Java Code Geeks
P
Proofpoint News Feed
大猫的无限游戏
大猫的无限游戏
Vercel News
Vercel News
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Last Week in AI
Last Week in AI
腾讯CDC
Cisco Talos Blog
Cisco Talos Blog
C
Check Point Blog
人人都是产品经理
人人都是产品经理
Forbes - Security
Forbes - Security
SecWiki News
SecWiki News
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
B
Blog
S
Secure Thoughts
T
Threat Research - Cisco Blogs
P
Privacy & Cybersecurity Law Blog
N
News | PayPal Newsroom
The GitHub Blog
The GitHub Blog
Recorded Future
Recorded Future
Google DeepMind News
Google DeepMind News
博客园 - 聂微东
V
Visual Studio Blog
L
LINUX DO - 最新话题
Recent Commits to openclaw:main
Recent Commits to openclaw:main
O
OpenAI News
Webroot Blog
Webroot Blog
Hacker News: Ask HN
Hacker News: Ask HN

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
The Icon Component I Keep Carrying
Tony Rowan · 2026-05-15 · via DEV Community

Nearly every project I've worked on has, at some point, had to answer the question of inlining SVGs into HTML. I've been refining my approach to this from project to project and now have something stable and reusable I just drop into anything new.

Why inline SVGs at all?

Embedding SVG markup directly in your HTML gives CSS full access to the SVG's internals — fill: currentColor, stroke control, hover states, all of it. It also means your icons come along for free with the HTML you're already serving, rather than as a separate request per image. If you need a deeper primer on the approach, CSS Tricks has a good one.

Phase 1: Reaching for a gem

The first time this came up, I immediately reached for a gem. Everyone does, especially early in your career. The excellent inline_svg was the obvious choice. It worked out of the box, slotted cleanly into ERB templates via a view helper, and had first-class support for a range of asset pipeline configurations — including Webpacker (Webpacker, not Shakapacker — yes, that long ago), which was always awkward to work with.

<%= inline_svg_tag "icons/arrow-right.svg", class: "size-6 text-gray-500" %>

Enter fullscreen mode Exit fullscreen mode

External dependencies come at a cost though. A general-purpose tool is, by definition, more complicated than you need it to be. inline_svg handled multiple asset pipeline strategies, SVG transformation pipelines, and a configuration surface to match. That flexibility meant it could be applied to pretty much any project. But icons, in practice, are done exactly one way per project — you pick a folder, you pick a naming convention, and that's it for the lifetime of the app. The complexity it brought for cases I'd never hit started to feel like dead weight: transitive dependencies and a configuration file the next person had to understand before changing anything.

Phase 2: Vendoring into /app/lib

A few years later I found myself needing to add inline SVGs again. This time around I vendored a small module into app/lib that read SVG files from a known path, did the minimal manipulation needed, and returned markup:

# app/lib/icon_renderer.rb
class IconRenderer
  class IconNotFoundError < StandardError; end

  def self.render(icon, size: "size-6", **options)
    new(icon, size: size, **options).render
  end

  def initialize(icon, size:, **options)
    @icon = icon
    @size = size
    @options = options
  end

  def render
    # parse SVG, inject attributes, return html_safe string
  end
end

Enter fullscreen mode Exit fullscreen mode

A view helper wired it into templates:

# app/helpers/icon_helper.rb
module IconHelper
  def icon(name, **options)
    IconRenderer.render(name, **options).html_safe
  end
end

Enter fullscreen mode Exit fullscreen mode

No external dependencies — nokogiri is bundled as part of Rails — a surface area I controlled completely, and logic I could read in full.

But this still wasn't perfect. The logic was split across two files that had to be understood and maintained together, even though they lived apart. I was also using a view helper to keep the ERB calls sane, and they had their own problems. They were globally included — icon :arrow_right could be defined anywhere, with nothing at the call site to tell you where to look. They were difficult to test in isolation. They accumulate quietly until your ApplicationHelper is a junk drawer.

These days, I reach for ViewComponent as my default for any view logic — reused partials, anything with non-trivial rendering behaviour, anything I want to test without standing up a full controller context. The icon renderer works fine and doesn't need much maintenance (it's still in use in that project), but it was exactly the kind of thing ViewComponent was made for.

Phase 3: A ViewComponent

On the next project, I dragged over my little module but pushed it into a ViewComponent. This is the version I carry around with me now. It encapsulates everything — parsing, attribute manipulation, error handling — in a single class.

I also took the opportunity to swap Nokogiri for Oga, a pure-Ruby XML parser with no native extensions — an idea I picked up from Kill Your Dependencies.

# app/components/icon_component.rb
# frozen_string_literal: true

class IconComponent < ViewComponent::Base
  class IconNotFoundError < StandardError; end

  attr_reader :icon, :size, :options

  def initialize(icon, size: "size-6", **options)
    @icon = icon
    @size = size
    @options = options
  end

  def call
    return render_icon_not_found if icon_not_found?

    svg = parsed_svg

    set_classes!(svg)
    set_aria_attributes!(svg, options[:aria])
    set_data_attributes!(svg, options[:data])
    set_base_attributes!(svg, base_attributes)
    set_role!(svg)

    svg.to_xml.strip.html_safe
  end

  private

  def icon_name
    icon.to_s
  end

  def class_list
    [size, options[:class]].compact_blank.join(" ")
  end

  def base_attributes
    options.except(:class, :aria, :data)
  end

  def set_classes!(svg)
    svg.set("class", (class_list.split + ["icon-#{icon_name.dasherize}"]).join(" "))
  end

  def set_aria_attributes!(svg, aria_attributes)
    aria_attributes&.each do |attribute, value|
      svg.set("aria-#{attribute.to_s.parameterize(preserve_case: true).dasherize}", value)
    end
  end

  def set_data_attributes!(svg, data_attributes)
    data_attributes&.each do |attribute, value|
      svg.set("data-#{attribute.to_s.parameterize(preserve_case: true).dasherize}", value)
    end
  end

  def set_base_attributes!(svg, attributes)
    attributes&.each do |attribute, value|
      svg.set(attribute.to_s.parameterize(preserve_case: true).dasherize, value)
    end
  end

  def set_role!(svg)
    svg.set("role", svg.get("role").presence || (svg.get("aria-label").blank? ? "presentation" : "img"))
  end

  def icon_not_found?
    !File.exist?(icon_asset_path)
  end

  def render_icon_not_found
    if Rails.env.local?
      raise IconNotFoundError, "Could not find icon: #{icon_name}"
    else
      "(Icon Not Found)"
    end
  end

  def parsed_svg
    Oga.parse_xml(File.read(icon_asset_path)).at_css("svg")
  end

  def icon_asset_path
    @_icon_asset_path ||= Rails.root.join("app/assets/images/icons/#{icon_name}.svg").to_s
  end
end

Enter fullscreen mode Exit fullscreen mode

Everything in there is something I've actually needed across the years, and nothing I haven't. Accessibility roles are set automatically (role="presentation" by default, role="img" when an aria-label is present). Size is a separate argument from other classes so you can vary icon sizes without rewriting class lists. Each icon gets an icon-{name} class — icon-arrow-right for :arrow_right — which makes targeting in tests and CSS straightforward without coupling to size or colour classes.

In use:

<%= render IconComponent.new(:arrow_right) %>
<%= render IconComponent.new(:arrow_right, class: "text-gray-500", aria: { label: "Next" }) %>
<%= render IconComponent.new(:arrow_right, size: "size-12") %>

Enter fullscreen mode Exit fullscreen mode

Where I landed

Took a few years and a few attempts to get there, but I now have a single file to drop into any new project. The specific choices are mine: Tailwind for CSS, ViewComponent for encapsulation, Oga for parsing. But the shape of it works regardless of your stack, and the gist is there if you want a starting point.


Originally posted on tonyrowan.tech