Skip to content

Instantly share code, notes, and snippets.

@josecanciani
Last active March 25, 2022 18:37
Show Gist options
  • Save josecanciani/c036b5c63befa4d09acb1767e2a0b889 to your computer and use it in GitHub Desktop.
Save josecanciani/c036b5c63befa4d09acb1767e2a0b889 to your computer and use it in GitHub Desktop.
This file allows creating simple objects in Bash scripts
#!/bin/bash -e
## This helper allows to create simulated objects in Bash
## Source: https://gist.github.com/josecanciani/c036b5c63befa4d09acb1767e2a0b889
##
## USAGE
##
## Lets create a person with first and last name
##
## source /path/to/where/you/downloaded/object.sh
## new person firstName lastName
## person.firstName = "Jose"
## person.lastName = "Canciani"
## echo "We've created a person named " $(person.firstName) $(person.lastName)
##
_OBJECT_CREATED=()
function _OBJECT_getClassCode() {
OBJECT_NAME=$1
shift
cat <<EOF
##
## This is an auto-generated code to create the ${OBJECT_NAME} object
##
# properies storage
${OBJECT_NAME}_OBJECT_PROPS=()
EOF
I=0
for PROP in "$@"
do
echo "${OBJECT_NAME}_OBJECT_PROP_ID_${PROP}=$I;"
((I=I+1))
done
cat <<EOF
${OBJECT_NAME}._get() {
echo \${${OBJECT_NAME}_OBJECT_PROPS[\$1]}
}
${OBJECT_NAME}._set() {
${OBJECT_NAME}_OBJECT_PROPS[\$1]=\$2
}
EOF
for PROP in "$@"
do
cat <<EOF
${OBJECT_NAME}.${PROP}() {
if [ "\$1" == "=" ]
then
${OBJECT_NAME}._set \$${OBJECT_NAME}_OBJECT_PROP_ID_${PROP} \$2
else
${OBJECT_NAME}._get \$${OBJECT_NAME}_OBJECT_PROP_ID_${PROP}
fi
}
EOF
done
cat <<EOF
##
## End of auto-generated code for the ${OBJECT_NAME} object
##
EOF
}
function new() {
if [[ " ${_OBJECT_CREATED[*]} " =~ " $1 " ]]; then echo "Found duplicated object $1" ; exit 1; fi
OBJECT_NAME="$1"
if ! [[ "$OBJECT_NAME" =~ ^[a-zA-Z0-9_]+$ ]]; then echo "Invalid object name $1" ; exit 1; fi
shift
for PROP in "$@"
do
if ! [[ "$PROP" =~ ^[a-zA-Z0-9_]+$ ]]; then echo "Invalid object property name $PROP"; exit 1; fi
done
_OBJECT_CREATED+=("$OBJECT_NAME")
if [ "$DEBUG" != "" ]; then _OBJECT_getClassCode "$OBJECT_NAME" $*; fi
eval "$(_OBJECT_getClassCode "$OBJECT_NAME" $*)"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment