From a464e769cc5871a136ea81851c58e25f1c4cc541 Mon Sep 17 00:00:00 2001 From: Anton Date: Sat, 11 Apr 2015 21:29:00 +0300 Subject: [PATCH] Optional auto-switching This commit provides the same workflow as chruby's auto.sh. When `auto.sh` script loaded into environment, it makes gem_home to automatically use a `.ruby-gemhome` to get project's `$GEM_HOME` path (`.ruby-gemhome` filename is customizable by the `$GEM_HOME_FILENAME` variable). --- README.md | 14 ++++++++++++++ share/gem_home/auto.sh | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 share/gem_home/auto.sh diff --git a/README.md b/README.md index cb32894..74126a3 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ Changes your `$GEM_HOME`. * Prepends the new `$GEM_HOME/bin` to `$PATH` so it takes precedence. * Compartmentalizes gems into `.gem/$ruby_engine/$ruby_version`. * Plays nicely with [RVM] and [chruby]. +* Optional auto-switching. * Supports [bash] and [zsh]. * Small (~90 LOC). * Has tests. @@ -100,6 +101,19 @@ fi This will prevent `gem_home` from accidentally being loaded by `/bin/sh`, which is not always the same as `/bin/bash`. +### Auto-switching + +This feature's workflow is similar to [chruby's `auth.sh`](https://github.com/postmodern/chruby/blob/master/share/chruby/auto.sh): + +If you want to auto-switch current `$GEM_HOME` when you cd between your different projects, simply load `auto.sh` in `~/.bashrc` or `~/.zshrc`: + +``` bash +source /usr/local/share/gem_home/gem_home.sh +source /usr/local/share/gem_home/auto.sh +``` + +gem_home will check the current and parent directories for a `.ruby-gemhome` file, which contains a path to the custom $GEM_HOME. + ## Uninstall After removing the `gem_home` configuration: diff --git a/share/gem_home/auto.sh b/share/gem_home/auto.sh new file mode 100644 index 0000000..5a80848 --- /dev/null +++ b/share/gem_home/auto.sh @@ -0,0 +1,35 @@ +unset GEM_HOME_AUTO + +if [ -z "$GEM_HOME_FILENAME" ]; then + export GEM_HOME_FILENAME=".ruby-gemhome" +fi + +function gem_home_auto() { + local dir="$PWD/" gem_dir + + until [[ -z "$dir" ]]; do + dir="${dir%/*}" + + if { read -e gem_dir <"$dir/$GEM_HOME_FILENAME"; } 2>/dev/null || [[ -n "$gem_dir" ]]; then + if [[ "$gem_dir" == "$GEM_HOME_AUTO" ]]; then return + else + GEM_HOME_AUTO="$gem_dir" + gem_home "$gem_dir" + return $? + fi + fi + done + + if [[ -n "$GEM_HOME_AUTO" ]]; then + gem_home - + unset GEM_HOME_AUTO + fi +} + +if [[ -n "$ZSH_VERSION" ]]; then + if [[ ! "$preexec_functions" == *chruby_auto* ]]; then + preexec_functions+=("gem_home_auto") + fi +elif [[ -n "$BASH_VERSION" ]]; then + trap '[[ "$BASH_COMMAND" != "$PROMPT_COMMAND" ]] && gem_home_auto' DEBUG +fi \ No newline at end of file