sixty4bit sixty4bit - 5 months ago 8
Ruby Question

Why do I get NameError with `bundle exec ruby [file]` given that the necessary gem is in Gemfile?

I'm doing some messing around to try to understand better how bundler works. I have just three files in my working directory:

Gemfile Gemfile.lock test.rb


All the Gemfile has is
gem "slop"
and
test.rb
looks like this:

puts Slop.parse


When I run
bundle exec test.rb
I get a
NameError
due to not having a
require
statement:

[ec2-user@xx my_app]$ bundle exec ruby test.rb
test.rb:1:in `<main>': uninitialized constant Slop (NameError)


But if I run
bundle console
, Bundler loads the gem correctly and I can run
Slop.parse
from the console without having to explicitly type
require "slop"
:

[ec2-user@xx my_app]$ bundle console
irb(main):001:0> Slop.parse
=> #<Slop::Result:0x00000001339838...


So what am I missing? I was under the impression that since I don't have
require: false
in my
Gemfile
,
Slop
should be loaded when I run
bundle exec ruby test.rb
and I shouldn't need to put the
require "slop"
line in the file.

Answer

You need to config bundler to require all gems on your Gemfile like this:

require 'rubygems'
require 'bundler/setup'
Bundler.require(:default)

Check the docs at http://bundler.io/v1.12/bundler_setup.html