tags:

views:

56

answers:

2

Sometimes I have seen following code.

gem 'factory_girl','= 1.2.3'
require 'factory_girl'

I tried to look at gem doc but could not find answer to the question of what does the first line do in code above?

+4  A: 

What you're looking for in the gem docs is about Coding with Rubygems.

The first line basically says "Hey, go get this gem with this version" from the install directory for gems and load it into the environment. This is mainly to help you add version dependencies to your requires instead of just doing require 'factory_girl' by itself.

Edit: To add on to Jörg's point below, I thought that Ryan Tomayko had a pretty good short and sweet article about why doing this is "wrong".

theIV
thanks. I guess I should have dug deeper into the doc. Also from the doc it seems I don't need both gem and require commands. It seems gem also requires.
Nadal
I thought just gem would require it. But just having gem 'factory_girl, '>= 1.2.4' is blowing up saying Factory is uninitialized Constant.
Nadal
Nope. The `gem` command will simply tell it which version of the gem you'd like to load, basically converting the gem name and version # to a load path (from my understanding). You still need to require the library. Sorry, I wasn't very clear on that from my answer.
theIV
I see. that makes sense. Thanks for clarification.
Nadal
+1  A: 

As @theIV already explained, this activates the factory_girl gem, using exactly (because of the = sign) version 1.2.3.

Note, however, that this is very bad practice and should never be done. If you activate gems manually inside your code, it means that people who do not use RubyGems can no longer use your code.

RubyGems is a package manager. Your code should never care about what package manager was used to install it. Some people prefer RubyGems, some dpkg/APT, some RPM/YUM, some RPM/APT, some RPM/URPMI, some RPM/YaST2, Portage, FreeBSD ports, pkgsrc, MacPorts, slashpackage, CoAPP, Conary, Slackware. There's tons of them. Some people like not to use any package manager at all. Or, they use RubyGems just for downloading, but then unpack the gem into their vendor directory.

All of this cannot possibly work, if you use the gem method in your code.

Jörg W Mittag
Did not know there were so many ways to manage your package. I see your point that require 'rubygems' or gem should not be used. Thanks.
Nadal
Sometimes it seems like all ruby documentation more than 6 months old should be removed from the internet.
Andrew Grimm