Sometimes when we write a Ruby script we need to use external gems to integrate with a third party API, or to facilitate the connection to a database.
For example, if you want to add coloring to produce messages
require 'rainbow'
puts Rainbow("My very important message in red").red
But when deploying this script, how can we ensure that these dependencies will be present? And will they be installed in the expected version for which our script has been tested?
What to do then? Creating a gem seems too heavy for our script, and it's not advisable to expect users to do the installation by themselves (it's okay for a gem but for a script that would start having 4-5 of them it's a lot).
Fortunately, Bundler is there for us, in fact, the installer offers a module that we can include in our script and that offers all the features of a Gemfile but to define our gems inside the script.
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'rainbow', '~> 3.0.0'
end
puts Rainbow("My very important message in red").red
Thus, when the script is launched, Bundler will check that the declared gems are installed, download them if necessary, and then load them automatically for use.
Top comments (4)
I really like this approach and using it for years now. I find it especially useful with things like rubocop, that bring quite a dependencies list which might be conflicting with runtime gems.
This is really cool. I wish that Ruby had a native way of handling dependencies like Deno has. We could reduce this code to:
Interesting idea, ๐ง
I use this in a variety of "script" type programs that I run only occasionally, such as to collect our data from Stripe and turn it into CSVs, or to process our PayPal logs, etc.