Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`require` vs. `gem` methods?

Tags:

ruby

require

gem

What's the difference between the require and gem methods?

For example, what's the difference betweenrequire 'minitest' and gem 'minitest'?

like image 413
ma11hew28 Avatar asked Feb 21 '14 15:02

ma11hew28


People also ask

What is require in gem file?

Gemfiles require at least one gem source, in the form of the URL for a RubyGems server. Generate a Gemfile with the default rubygems.org source by running bundle init . If you can, use https so your connection to the rubygems.org server will be verified with SSL.

What does gem require false mean?

You use :require => false when you want the gem to be installed but not "required". So in the example you gave: gem 'whenever', :require => false when someone runs bundle install the whenever gem would be installed as with gem install whenever .

What is require RubyGems?

require 'rubygems' will adjust the Ruby loadpath allowing you to successfully require the gems you installed through rubygems, without getting a LoadError: no such file to load -- sinatra .

What does require do in Rails?

require can also be used to load only a part of a gem, like an extension to it. Then it is of course required where the configuration is. You might be concerned if you work in a multi-threaded environment, as they are some problems with that. You must then ensure everything is loaded before having your threads running.


2 Answers

Say you have two versions of the gem foo installed:

$ gem list foo

*** LOCAL GEMS ***

foo (2.0.1, 2.0.0)

If you use only require, the newest version will be loaded by default:

require 'foo'       # => true

Foo::VERSION        # => "2.0.1"

If you use gem before calling require, you can specify a different version to use:

gem 'foo', '2.0.0'  # => true
require 'foo'       # => true

Foo::VERSION        # => "2.0.0"

Note: using gem without subsequently calling require does not load the gem.

gem 'foo'           # => true

Foo::VERSION        # => NameError: uninitialized constant Foo
like image 167
user513951 Avatar answered Oct 03 '22 21:10

user513951


Kernel#require activates the latest version of a gem.

Kernel#gem (added by RubyGems) allows activation of specific gem versions.

like image 43
ma11hew28 Avatar answered Oct 03 '22 22:10

ma11hew28