Skip to content

Instantly share code, notes, and snippets.

@travisbhartwell
Created December 10, 2024 22:00
Show Gist options
  • Save travisbhartwell/6eec91becd226385947c4fbca786215d to your computer and use it in GitHub Desktop.
Save travisbhartwell/6eec91becd226385947c4fbca786215d to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# -*- mode: shell-script; sh-shell: bash; sh-basic-offset: 4; sh-indentation: 4; coding: utf-8 -*-
# shellcheck shell=bash
set -o nounset -o errexit -o errtrace -o pipefail
readonly _NAME_FIELD='name'
readonly _ACTION_FIELD='action'
function widget:get_name() {
local -n widget_struct_ref="${1}"
echo "${widget_struct_ref["${_NAME_FIELD}"]}"
}
function widget:_get_action() {
local -n widget_struct_ref="${1}"
echo "${widget_struct_ref["${_ACTION_FIELD}"]}"
}
function widget:do_action() {
local -n widget_struct_ref="${1}"
local action
action=$(widget:_get_action "${!widget_struct_ref}")
readonly action
"${action}" "${!widget_struct_ref}"
}
function english_widget:action() {
local -n widget_struct_ref="${1}"
local name
name=$(widget:get_name "${!widget_struct_ref}")
readonly name
echo "Hello, ${name}!"
}
function english_widget:new() {
local -n widget_struct_ref="${1}"
local -r name="${2}"
widget_struct_ref["${_NAME_FIELD}"]="${name}"
widget_struct_ref["${_ACTION_FIELD}"]="english_widget:action"
}
function german_widget:action() {
local -n widget_struct_ref="${1}"
local name
name=$(widget:get_name "${!widget_struct_ref}")
readonly name
echo "Guten tag, ${name}!"
}
function german_widget:new() {
local -n widget_struct_ref="${1}"
local -r name="${2}"
widget_struct_ref["${_NAME_FIELD}"]="${name}"
widget_struct_ref["${_ACTION_FIELD}"]="german_widget:action"
}
function main() {
local -A travis_widget
english_widget:new travis_widget "Travis"
local -A hans_widget
german_widget:new hans_widget "Hans"
echo "Greeting Travis in English:"
widget:do_action travis_widget
echo "Greeting Hans auf Deutsch:"
widget:do_action hans_widget
}
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment