Howto: Require a gem that is not in Gemfile

Posted About 7 years ago. Visible to the public.

In case you want to require a gem, that is not in the Gemfile of you bundle and therefore not in your loadpath, you need to add the path manually and require the gem afterwards.

Expected error

Requiring a gem, that is not in the Gemfile or .gemspec, will cause an LoadError exception:

require 'example_gem' => LoadError: cannot load such file -- example_gem

Adding a gem to the loadpath temporary

  1. You need to install the gem

gem install 'example_gem'

  1. Then you need to require the path where the gem was installed to:
$: << '/home/xxx/.rvm/rubies/ruby-x.x.x/lib/ruby/x.x.x/gems/example_gem-x.x.x'
$: << '/home/xxx/.rvm/rubies/ruby-x.x.x/lib/ruby/x.x.x/gems/example_gem-x.x.x/lib'

Note: To find out the path quickly just look at $: to get the base path of your ruby dir and then append the gem with version of the output of gem install. The Ruby version can be found out with ruby -v.

  1. Then require the gem
require 'example_gem => true

Outline

Usually the method above is just needed e.g. for debugging. For all other cases you should add the gem to Gemfile or .gemspec . There also exists a development group in the Gemfile or .gemspec, in case you do not want to have a development gem on production servers.

Last edit
Over 2 years ago
Emanuel
License
Source code in this card is licensed under the MIT License.
Posted by Emanuel to makandra dev (2017-05-10 07:11)