Skip to content

Instantly share code, notes, and snippets.

@hopsoft
Last active July 24, 2024 19:33
Show Gist options
  • Save hopsoft/d7c96372eeedf73b740e450e059a1d22 to your computer and use it in GitHub Desktop.
Save hopsoft/d7c96372eeedf73b740e450e059a1d22 to your computer and use it in GitHub Desktop.
Simple Template Rendering

Simple Template Rendering

I'm experimenting with a simple template rendering solution that leverages Ruby's native String formatting. It feels a little bit like Mustache templates. Note that this demo adds new "formatting specifiers" to support Rainbow color mechanics.

Tip

See the files below for the implementation... and note that this is simply a proof of concept (POC)

Usage

ruby demo.rb

Outupt

CleanShot 2024-07-24 at 13 24 29@2x

require_relative "renderer"
template = <<~TEMPLATE
Hello %{name}green!
Number: %<number>03d
Message: %{message}orange
TEMPLATE
renderer = Renderer.new(template)
puts renderer.render(name: "Nate", number: 1, message: "This is cool!")
require "rainbow"
# Proof of concept of a simple template renderer that uses Ruby's standard String formatting
# with the addition of custom "formatting specifiers" that support Rainbow colors
class Renderer
include Rainbow
COLORS = Rainbow::X11ColorNames::NAMES.keys
PATTERN = /%\{(\w+)\}(#{COLORS.join '|'})/
def initialize(template)
@template = template
end
attr_reader :template
def render(**locals)
result = format(template, **locals) # custom formatting
result % locals # native formatting
end
def format(value, **locals)
copy = value.dup
value.scan(PATTERN) do |(key, color)|
placeholder = "%{#{key}}#{color}"
value = locals[key.to_sym]
copy = copy.gsub(placeholder, Rainbow(value).public_send(color))
end
copy
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment