Skip to content

Code Syntax Highlighting Showcase

I wanted to test the syntax highlighting on my blog, so I decided to share some code snippets from different programming languages.

I've used variations of these snippets in real projects.

Ruby

It is a single-file Rails application used for testing ActiveRecord methods. It's based on the official Rails issue template, but I've modified it to use PostgreSQL as the database. There are also templates available to test other parts of a Rails application.

# frozen_string_literal: true
 
require "bundler/inline"
 
gemfile(true) do
  source "https://rubygems.org"
 
  gem "rails"
  gem "pg"
end
 
require "active_record"
require "logger"
 
ActiveRecord::Base.establish_connection(
  adapter: "postgresql",
  database: "postgres",
  host: "localhost",
  username: "postgres",
  password: "",
  port: 5432
)
 
ActiveRecord::Base.connection.drop_database("rails_blog_demo") rescue nil
ActiveRecord::Base.connection.create_database("rails_blog_demo")
ActiveRecord::Base.establish_connection(
  adapter: "postgresql",
  database: "rails_blog_demo",
  host: "localhost",
  username: "postgres",
  password: "",
  port: 5432
)
 
ActiveRecord::Base.logger = Logger.new(STDOUT)
 
ActiveRecord::Schema.define do
  create_table :posts, force: true do |t|
    t.string :title
    t.text :content
    t.timestamps
  end
 
  create_table :comments, force: true do |t|
    t.belongs_to :post, null: false
    t.text :body
    t.timestamps
  end
end
 
class Post < ActiveRecord::Base
  has_many :comments, dependent: :destroy
end
 
class Comment < ActiveRecord::Base
  belongs_to :post
end
 
post = Post.create!(title: "Sample Post", content: "This is a sample blog post.")
comment = post.comments.create!(body: "Great post!")
 
puts "Post: #{post.title}"
puts "Comment: #{comment.body}"
puts "Post has #{post.comments.count} comments"

CSS

CSS that makes a circle with a colorful gradient that spins, changes color, and animates.

.circle {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  background: linear-gradient(45deg, #60a5fa, #a855f7);
  margin: 20px auto;
  animation: 
      rotate 4s linear infinite,
      colorShift 6s ease-in-out infinite,
      bounce 3s ease-in-out infinite;
}
 
@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
 
@keyframes colorShift {
  0% { filter: hue-rotate(0deg) brightness(1); }
  25% { filter: hue-rotate(90deg) brightness(1.2); }
  50% { filter: hue-rotate(180deg) brightness(0.9); }
  75% { filter: hue-rotate(270deg) brightness(1.1); }
  100% { filter: hue-rotate(360deg) brightness(1); }
}
 
@keyframes bounce {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.05); }
}

Go

A Go program that parses IPv4 and IPv6 addresses.

package main
 
import (
	"fmt"
	"log"
	"net"
)
 
func main() {
	ipv4Addr, ipv4Net, err := net.ParseCIDR("192.0.2.1/24")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(ipv4Addr)
	fmt.Println(ipv4Net)
 
	ipv6Addr, ipv6Net, err := net.ParseCIDR("2001:db8:a0b:12f0::1/32")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(ipv6Addr)
	fmt.Println(ipv6Net)
}

JavaScript/TypeScript

A simple Rock Paper Scissors game built with React where you can play against the computer:

Rock Paper Scissors

// RockPaperScissors.tsx
import React, { useState } from 'react';
 
const choices = ['Rock', 'Paper', 'Scissors'] as const;
type Choice = typeof choices[number];
 
const getWinner = (player: Choice, cpu: Choice) => {
  if (player === cpu) return "It's a tie!";
  if (
    (player === 'Rock' && cpu === 'Scissors') ||
    (player === 'Paper' && cpu === 'Rock') ||
    (player === 'Scissors' && cpu === 'Paper')
  ) return 'You win!';
  return 'You lose!';
};
 
export default function RockPaperScissors() {
  const [player, setPlayer] = useState<Choice | null>(null);
  const [cpu, setCpu] = useState<Choice | null>(null);
  const [result, setResult] = useState('');
 
  const play = (choice: Choice) => {
    const cpuChoice = choices[Math.floor(Math.random() * 3)];
    setPlayer(choice);
    setCpu(cpuChoice);
    setResult(getWinner(choice, cpuChoice));
  };
 
  return (
    <div style={{ textAlign: 'center', fontFamily: 'sans-serif' }}>
      <h1>Rock Paper Scissors</h1>
      {choices.map(c => (
        <button key={c} onClick={() => play(c)} style={{ margin: '0 10px' }}>
          {c}
        </button>
      ))}
      {player && cpu && (
        <div>
          <p>You chose: {player}</p>
          <p>Computer chose: {cpu}</p>
          <h2>{result}</h2>
        </div>
      )}
    </div>
  );
}

SQL

SQL query to find the management chain of a user:

CREATE TABLE users (id SERIAL PRIMARY KEY,
                              name TEXT, manager_id INT REFERENCES users(id));
 
WITH RECURSIVE management_chain AS
  (SELECT id,
          name,
          manager_id,
          1 AS LEVEL
   FROM users
   WHERE id = 7
   UNION ALL SELECT u.id,
                    u.name,
                    u.manager_id,
                    mc.level + 1
   FROM users u
   JOIN management_chain mc ON u.id = mc.manager_id)
SELECT *
FROM management_chain
ORDER BY LEVEL;