Skip to content

Instantly share code, notes, and snippets.

@havenwood
Created July 3, 2023 17:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save havenwood/8fd44cca7e8f9ec967c80f548db06094 to your computer and use it in GitHub Desktop.
Save havenwood/8fd44cca7e8f9ec967c80f548db06094 to your computer and use it in GitHub Desktop.
Example of a Curses colors registry Singleton for IRC
# frozen_string_literal: true
require 'curses'
require 'singleton'
module Isene
class ColorRegistry
include Singleton
attr_reader :colors
attr_reader :pairs
attr_reader :modified_colors
attr_reader :modified_pairs
def initialize
Curses.start_color
@colors = Array.new(Curses.colors) { [_1, Curses.color_pair(_1)] }
@pairs = @colors.each_with_index.to_h
@modified_colors = {}
@modified_pairs = {}
end
def init_pair(index, foreground, background)
return unless Curses.init_pair(index, foreground, background)
pair = [foreground, background]
@pairs[pair] = index
@colors[index] = pair
@modified_pairs[pair] = index
@modified_colors[index] = pair
end
def fetch(...) = @pairs.fetch(...)
def color(index) = @colors[index]
instance.public_methods(false).each do |method_name|
define_singleton_method(method_name) do |*args, &block|
instance.public_send(method_name, *args, &block)
end
end
end
end
require_relative 'color_registry'
Isene::ColorRegistry.init_pair 255, Curses::COLOR_BLACK, Curses::COLOR_WHITE
Isene::ColorRegistry.fetch [Curses::COLOR_BLACK, Curses::COLOR_WHITE]
#=> 255
Isene::ColorRegistry.modified_pairs
#=> {[0, 7]=>255}
Isene::ColorRegistry.modified_colors
#=> {255=>[0, 7]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment