Rails' alias_method_chain for Bash
Rails has a great trick for monkey-patching in decorators, called aliasmethodchain. While long-term use is perhaps discouraged, it's awesome if you need to just insert some behavior in a hurry.
Using bash's introspection support, we can achieve the same thing for shell functions:
function decorate {
local base=$1
local feature=$2
local undecorated="${base}_without_${feature}"
local decorated="${base}_with_${feature}"
# Define $undecorated with $base's body
eval "$(echo 'function' $undecorated; declare -f $base | tail -n +2)"
# Define $base with $decorated's body
eval "$(echo 'function' $base; declare -f $decorated | tail -n +2)"
}
Here's how to use it:
$ function theirfunc { echo do their thing; }
$ function theirfunc_with_mything {
> echo do my thing
> theirfunc_without_mything
> }
$ decorate theirfunc mything
$ theirfunc
do my thing
do their thing
Reposted from SO: http://stackoverflow.com/a/4727925/580412
Written by Phil Smith
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Shell
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#