If you accidentally run gem install without sudo you’ll end up with the gem installed into your ~/.gem directory instead of your system gem path. This can cause annoyances, one of which I mentioned here.
To protect yourself from your own stupidity just deny yourself access to the directory:
chmod -R u-w ~/.gem
Now try installing a gem without sudo and you’ll get:
$ gem install hpricot
WARNING: Installing to ~/.gem since /usr/lib/ruby/gems/1.8 and
/usr/bin aren't both writable.
ERROR: While executing gem ... (Gem::FilePermissionError)
You don't have write permissions into the /home/me/.gem/ruby/1.8 directory.
This has already saved me a few times. Thanks to Arild Shirazi for the suggestion.

What about –no-user-install in your gemrc?
Comment by daeltar — March 16, 2009 @ 10:49 pm
Never thought to do this, but I do always set alias gem=’sudo gem’ in my ~/.bashrc. Seems to work alright.
Comment by Danny Tatom — March 17, 2009 @ 5:31 am
Can I safely remove everything below ~/.gem, just leaving the dir itself?
Also, ’sudo rake gems:unpack’ inside a Rails app directory, never seems to work in my Mac. Using Rails 2.2.
Comment by Levy Carneiro Jr — March 17, 2009 @ 11:58 am
LOL! Yesterday’s brutal hack has become today’s standard procedure. Beautiful.
I did a ‘chmod 000 ~/.gem’ a few months ago. Happiness has ensued.
@daeltar – Thanks for posting the “correct” solution!
Comment by David Brady — March 17, 2009 @ 2:46 pm
Yeah, –no-user-install may become the default since this seems to bite a lot of folks. It’s important that it’s easy to install in user directories for things like shared hosting, but auto-fallback is pretty error-prone.
Comment by Phil — March 17, 2009 @ 10:18 pm
@dealter, @david
Actually the user_install config option isn’t passed through to Gem::DependencyInstaller.new which is what calls Gem::Installer.new which is what checks if user_install is set.
see commands/install_command:68
Comment by coderrr — March 17, 2009 @ 11:46 pm
[...] Protecting your ~/.gem directory « coderrr [...]
Pingback by Ennuyer.net » Blog Archive » Rails Reading - November 24, 2009 — November 24, 2009 @ 10:44 pm
THANK YOU!
Comment by Stew — December 4, 2009 @ 4:27 am