Search code examples
rubybundler

Require files from gem in Ruby script without bundle exec


I have a script that needs to require specific files out of gems defined in the project Gemfile.

#!/usr/bin/env ruby
require 'some_gem/helpers/some_helper'

... rest of script

When I run the script, I get an error about not being able to load some_helper.rb. If I run with bundle exec command... then everything works.
I understand that bundle exec exposes the Gems to the $LOAD_PATH which lets require work. Is there a way to move that capability into the script so users don't have to type bundle exec?

Do I just need to add require "bundler/setup" to the script before I require the gem files?


Solution

  • http://bundler.io/v1.12/#getting-started

    :)

    #!/usr/bin/env ruby
    require 'rubygems' # because reasons.. most probably it is not needed unless you are using really old ruby where it is not loaded by default
                       # also at the moment rubygems and bundler are being merged :) 
    require 'bundler/setup' # for things installed with bundler
    require 'some_gem/helpers/some_helper'
    

    You can also check e.g. http://mislav.net/2013/01/understanding-binstubs/