Using bundler inline

A little while ago someone showed me a pretty cool feature of Bundler that I didn’t know about: you can use it inline in a Ruby script without having to create a separate Gemfile. This is very convenient for writing little utility scripts.

To use bundler this way you start with a require bundler/inline followed by a gemfile block that contains the content that you would have put in the Gemfile if you would have had to create one. When you then execute the script with Ruby Bundler will first install the required gems (if needed) before executing your code.

Here’s an example that uses the HTTPClient gem to check your external IP address (using the same endpoint I made for my article on obtaining your external IP address from the command-line):

require 'bundler/inline'

gemfile do
  source 'https://rubygems.org'
  gem 'httpclient'
end

client = HTTPClient.new
puts client.get('https://ip.5ec.nl').body

If you execute this script for the first time it will pause a moment to install the HTTPClient gem, the next time you execute it will work without delay.

This and other features of Bundler are well documented on the official Bundler documentation pages, it’s well worth having a look around there.

If you have feedback on this article or have questions based on its contents then feel free to reach out to me on Twitter or through e-mail.