Hemanth.HM

A Computer Polyglot, CLI + WEB ♥'r.

Auto Require Ruby Gems

| Comments

If you have coded some ruby you would have seen the LoadError : 'require': no such file to load -- rubygems (LoadError) in case of the required gem is missing (not installed) or the gem path is screwed up!

Here is a simple silly old trick :

1
2
3
4
5
6
7
8
alias old_require require
def load_gem(gem)
  old_require gem
  rescue LoadError => e
    print "'#{gem}' can't be found, trying to install it..."
    system("gem install  #{gem} --no-ri --no-rdoc") ;
    Gem.clear_paths() && require(gem) && puts("loading '#{gem}' ok!")
end

Using it :

1
2
3
4
5
6
7
8
1.9.2-p320 :020 > require 'xkcd'
'xkcd' can't be found, trying to install it..
Fetching: xkcd-1.0.1.gem (100%)
Successfully installed xkcd-1.0.1
Fetching: mini_portile-0.5.1.gem (100%)
Successfully installed mini_portile-0.5.1
2 gems installed
 => nil

Well something like Bundler must be used at any case! This is just some undocumented old code.

Comments