Skip to content

Instantly share code, notes, and snippets.

View havenwood's full-sized avatar
:octocat:

Shannon Skipper havenwood

:octocat:
  • Leafly
  • Ashland, Oregon
  • 06:55 (UTC -08:00)
View GitHub Profile
@havenwood
havenwood / shareable_lambda.rb
Created October 31, 2026 05:34
A refinement implementing a `lambda(shareable: true)` nicety
module ShareableLambda
UNSET = Object.new.freeze
private_constant :UNSET
refine Kernel do
private
def lambda(shareable: false, self: UNSET, &block)
receiver = {self:}[:self]
require_relative "enumerable-parallel"
using Enumerable::Parallel.new(pool_size: 2)
(1..4).each do |number|
sleep 1
puts "#{number}\n"
end
##
# One second later...
@havenwood
havenwood / color.rb
Created July 14, 2026 17:43
An example pattern matching mixin for data objects
require_relative "pattern_matchable"
class Color
extend PatternMatchable
array_pattern :red, :green, :blue
hash_pattern :red, :green, :blue,
hex: -> { format "#%06x", packed },
brightness: -> { (red * 299 + green * 587 + blue * 114).fdiv(1_000) }
@havenwood
havenwood / klass.rb
Created July 4, 2026 03:37
superclass=
require "fiddle"
require_relative "settable_superclass"
class Klass
using SettableSuperclass
HEAP_TYPE = ->(obj) { Fiddle::Pointer.new(Fiddle.dlwrap(obj))[0, Fiddle::SIZEOF_VOIDP].unpack1("J") & 0x1f }
private_constant :HEAP_TYPE
@havenwood
havenwood / example.rb
Last active July 3, 2026 21:23
A Rust-like `Reverse` for Ruby
[2, 3, 1].sort_by { Reverse[it] }
#=> 3, 2, 1
@havenwood
havenwood / options.rb
Created June 19, 2026 15:38
Parsing Ruby options into Data
require 'optparse'
module Kernel
def OptionParser(&)
fields = OptionParser.new(&).top.list.filter_map do |option|
if option.is_a?(OptionParser::Switch)
name = option.long&.first || option.short&.first
name.delete_prefix('-').delete_prefix('-').to_sym
end
end
@havenwood
havenwood / alert.rb
Created May 3, 2026 15:33
An example showing a class inheriting from Module for custom exceptions
class Alert < Module
COLORS = {red: 31, yellow: 33, blue: 34, magenta: 35, cyan: 36}
def initialize(message: nil, color: :red)
super()
@message = message
@color = COLORS.fetch(color)
end
def included(base)
@havenwood
havenwood / README.rdoc
Created April 22, 2026 16:04
Single-file version control implemented in a single Ruby file

Single-file version control. Lighter than RCS.

cp rev.rb /usr/local/bin/rev

Requires Ruby, diff and patch. Colored output when git is available.

@havenwood
havenwood / example.rb
Created March 13, 2026 17:57
An example of double-checked locking with a Mutex for safe concurrent access
module Example
ONCE = Once.new
def self.once
ONCE.call do
# work
end
end
end
defmodule FizzBuzz.Native do
@moduledoc false
use Rustler, otp_app: :fizz_buzz
def classify(_nums), do: :erlang.nif_error(:nif_not_loaded)
end