What's the difference between the require
and gem
methods?
For example, what's the difference betweenrequire 'minitest'
and gem 'minitest'
?
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.
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 .
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 .
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.
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
Kernel#require activates the latest version of a gem.
Kernel#gem (added by RubyGems) allows activation of specific gem versions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With