Last active
December 14, 2015 15:29
-
-
Save cwgem/5107976 to your computer and use it in GitHub Desktop.
Hacking around with the crazy idea of object oriented in bash because I can
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| # @cwgem (Chris White) | |
| # Screwing around with the concept of objects in bash | |
| # Not POSIX compliant and as with many bash scripts a huge hack ;) | |
| # Hold "object properties" in a global associative array | |
| # So far this means basically static objects with no instances | |
| declare -A _Person | |
| # The object is just a function in the end | |
| Person() { | |
| # Which takes a method as an argument | |
| local method=$1 | |
| local this=${FUNCNAME} | |
| # global scope can't see it wohoo | |
| SetProperty() { | |
| _Person[$1]=$2; | |
| } | |
| # A setter method | |
| Person.SetName() { | |
| SetProperty first_name $1 | |
| SetProperty last_name $2 | |
| } | |
| # And a standard method | |
| Person.SayName() { | |
| # Grab "class properties" from the global array to ensure state | |
| echo "Hello ${_Person[first_name]} ${_Person[last_name]}" | |
| } | |
| # FUNCNAME is set by bash to be the name of the | |
| # function, person and we just latch on a period | |
| # to indicate the "method". Then we pass all other | |
| # arguments after the method name to the method | |
| "${this}.${method}" ${@:2:$#} | |
| } | |
| # Sending an "object" a "message" type of call style | |
| Person SetName "Chris" "White" | |
| Person SayName |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment