Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I have a gem installed but require 'gemname' does not work. Why?

Tags:

ruby

rubygems

The question I'm really asking is why require does not take the name of the gem. Also, In the case that it doesn't, what's the easiest way to find the secret incantation to require the damn thing!?

As an example if I have memcache-client installed then I have to require it using

require 'rubygems' require 'memcache' 
like image 405
mloughran Avatar asked Sep 25 '08 12:09

mloughran


People also ask

How do I know if gem is installed?

Since your goal is to verify a gem is installed with the correct version, use gem list . You can limit to the specific gem by using gem list data_mapper . To verify that it's installed and working, you'll have to try to require the gem and then use it in your code.

How does gem install work?

What does gem install do? gem install , in its simplest form, does something kind of like this. It grabs the gem and puts its files into a special directory on your system. You can see where gem install will install your gems if you run gem environment (look for the INSTALLATION DIRECTORY: line):


2 Answers

My system also doesn't seem to know about RubyGems' existence - unless I tell it to. The 'require' command gets overwritten by RubyGems so it can load gems, but unless you have RubyGems already required it has no idea how to do that. So if you're writing your own, you can do:

require 'rubygems' require 'gem-name-here' 

If you're running someone else's code, you can do it on the command line with:

ruby -r rubygems script.rb 

Also, there's an environment variable Ruby uses to determine what it should load up on startup:

export RUBYOPT=rubygems 

(from http://www.rubygems.org/read/chapter/3. The environment variable thing was pointed out to me by Orion Edwards)

(If "require 'rubygems' doesn't work for you, however, this advice is of limited help :)

like image 60
Atiaxi Avatar answered Sep 21 '22 13:09

Atiaxi


There is no standard for what the file you need to include is. However there are some commonly followed conventions that you can can follow try and make use of:

  • Often the file is called the same name as the gem. So require mygem will work.
  • Often the file is the only .rb file in the lib subdirectory of the gem, So if you can get the name of the gem (maybe you are itterating through vendor/gems in a pre 2.1 rails project), then you can inspect #{gemname}/lib for .rb files, and if there is only one, its a pretty good bet that is the one to require

If all of that works, then all you can do is look into the gem's directory (which you can find by running gem environment | grep INSTALLATION | awk '{print $4}' and looking in the lib directory, You will probably need to read the files and hope there is a comment explaining what to do

like image 29
Laurie Young Avatar answered Sep 19 '22 13:09

Laurie Young