AI Code Explainer — Ruby source
Paste any code snippet and get a plain-language explanation from an LLM — beginner, developer, or expert depth — with your own free Groq key, straight from your browser.
This is the Ruby implementation — the same logic the interactive tool runs, in a shareable, citable form.
# code-explainer — language guessing, depth-graded prompts, reply cleanup.
#
# Language: Ruby (3.x, standard library only — Regexp is a literal of the
# language, but its \w / \b are encoding-aware, so each rule is
# prefixed with the (?a) ASCII-mode switch to pin them to the
# JavaScript semantics the TS rules assume)
# CosmoDev polyglot showcase port of the `code-explainer` tool, ported from
# src/lib/code-explainer.ts (the canonical TypeScript implementation).
#
# Why this file exists: the whole explainer pipeline is three pure functions
# — guess which language a paste is, wrap it in a depth-graded chat prompt,
# strip code fences from the reply — so every runtime runs the identical
# heuristics. Two dialect notes: Ruby's ^ and $ are always line anchors (the
# TS /m flag is the default, /m means dot-matches-newline here), and Ruby's
# . never crosses a newline by default, just like the TS rules assume.
#
# display source — part of CosmoDev's polyglot tool pages.
# frozen_string_literal: true
# Depth knob for the prompt: how much explanation contract the model gets.
LEVELS = %w[beginner developer expert].freeze
# Guess the language from (and prompt with) at most this many chars.
MAX_CODE_CHARS = 12_000
# Per-level explanation contract, verbatim from the TS lib. An unknown level
# hashes to nil, which interpolates as "" — not the TS template's literal
# "undefined".
LEVEL_CONTRACT = {
"beginner" =>
"Explain for a smart newcomer: no unexplained jargon, short sentences, " \
"one everyday analogy if it helps. Say what it does first, then how, " \
"step by step.",
"developer" =>
"Explain for a working developer: concise and practical. Lead with what " \
"it does, then the flow, the patterns used, and the pitfalls an editor " \
"should catch.",
"expert" =>
"Explain for an expert: dense and precise. Cover invariants, complexity, " \
"edge cases, and anything subtle an experienced reviewer would flag.",
}.freeze
# Cheap keyword heuristics — enough to name the language in the prompt so the
# model starts right; never a language detector. First match wins, so order
# matters: go before rust before python before the web trio.
RULES = [
["go", /(?a)\bpackage\s+\w+|\bfunc\s+\w+|:=/],
["rust", /(?a)\bfn\s+\w+|\blet\s+mut\b|\bimpl\b/],
["python", /(?a)\bdef\s+\w+\s*\(|\bprint\s*\(|\bimport\s+\w+\s*$/],
["sql", /(?a)\bSELECT\b.+\bFROM\b/i],
["typescript", /(?a)\binterface\s+\w+\s*\{|\btype\s+\w+\s*=|:\s*(string|number|boolean)\b/],
["javascript", /(?a)\bconst\s+\w+\s*=|=>|console\.log/],
["css", /(?a)[.#]?[\w-]+\s*\{[^}]*:[^}]*;/],
["html", /(?a)<\/?[a-z][\w-]*(\s+[\w-]+="[^"]*")*\s*\/?>/i],
].freeze
# Guess which language a code sample is written in. Falls back to "text"
# when no rule matches, so the prompt can tell the model to reason about the
# paste as pseudocode instead of pretending to know better.
def guess_language(code)
RULES.each { |lang, re| return lang if re.match?(code) }
"text"
end
# Build the [system, user] chat messages for the provider layer. The code is
# truncated BEFORE guessing: the heuristics only need a sample, and running
# them over a 30k-char paste is pure waste.
def build_prompt_messages(code, level:)
truncated = code.length > MAX_CODE_CHARS
body = truncated ? "#{code[0, MAX_CODE_CHARS]}\n… (code truncated)" : code
lang = guess_language(body)
uncertainty =
lang == "text" ? " (no clear language — say so and reason about it as pseudocode)" : ""
[
{
role: "system",
content: "You explain code. #{LEVEL_CONTRACT[level]} The code appears to be " \
"#{lang}#{uncertainty}. Use short paragraphs or bullets; markdown is fine."
},
{ role: "user", content: body }
]
end
# Clean the model's reply into displayable explanation text: strip markdown
# code fences, then trim. Returns nil only when nothing survives cleaning —
# there is no strict format contract beyond "non-empty".
def parse_explanation(text)
cleaned = text.gsub(/```[a-z]*\n?/, "").strip
cleaned.empty? ? nil : cleaned
end
if $PROGRAM_NAME == __FILE__
puts guess_language("package main\nfunc main() {}") # go
puts guess_language("def hi():\n print(hi())") # python
puts guess_language("SELECT id FROM users") # sql
puts guess_language("plain thoughts") # text
build_prompt_messages("x = 1", level: "expert").each do |message|
puts "#{message[:role]}: #{message[:content]}"
end
puts parse_explanation("```python\nprint('hi')\n```\nIt prints!")
puts parse_explanation("```\n```") || "(nil)"
end
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →