0

Just playing around with Ruby and have this very basic example

runner.rb:

require "bundler/setup"
include Mongo

mongo_client = MongoClient.new("localhost", 27017)
#mongo_client.database_names # lists all database names
#mongo_client.database_info.each { |info| puts info.inspect }

db = mongo_client.db("james_safety")

coll = db.collection("safety")

puts "above"

10.times { |i| coll.insert("i" => i) }


puts "Hello World"

Gemfile:

source :rubygems
gem 'mongo'

bundle output:

Using bson (1.8.2) 
Using mongo (1.8.2) 
Using bundler (1.2.2) 
Your bundle is complete! Use `bundle show [gemname]` to see where a bundled gem is installed.

When I try to run ruby runner.rb, I get this error:

/Users/Tyler/Development/Ruby/JamesSaftey/runner.rb:2:in `<top (required)>': uninitialized constant Mongo (NameError)
    from -e:1:in `load'
    from -e:1:in `<main>'

If I require 'mongo' in runner.rb, it works just fine (I installed the gem outside of the Gemfile).

I also tried require 'rubygems'. No difference.

Am I just misconfiguring my ruby file to use the Gemfile?

Ruby 1.9.3

Tyler DeWitt
  • 23,366
  • 38
  • 119
  • 196

1 Answers1

0

Even if a gem is in the gemfile, you need to require it, or do the following in your ruby file so all the bundled gems are required :

Bundler.require(:default)

More infos here

Intrepidd
  • 19,772
  • 6
  • 55
  • 63
  • The first part (just adding the `require` to the `Gemfile` did not work), however, adding `Bundler.require(:default)` to the ruby file did work. Thanks – Tyler DeWitt Mar 03 '13 at 18:45
  • My bad, the first part just indicates to bundler which file to require if it differs from the gem name. Editing ... – Intrepidd Mar 03 '13 at 18:46