Skip to content

Instantly share code, notes, and snippets.

@zverok
Last active August 14, 2016 09:04
Show Gist options
  • Save zverok/7ff41fcede80bf9733d97a008f10cc1c to your computer and use it in GitHub Desktop.
Save zverok/7ff41fcede80bf9733d97a008f10cc1c to your computer and use it in GitHub Desktop.
# Small thing for installing gems on-the-fly.
# Useful for "self-contained" scripts, too small to be
# distributed with own Gemfile & README and stuff.
#
# Usage:
#
# gimme_gem 'sequel' # Checks OR installs the gem
# Sequel.connect 'mysql://....'
#
# All credits for managing RubyGems code goes to author
# of this gist: https://gist.github.com/adamjmurray/3154437
def gimme_gem(name, version = nil)
gem name, version
require name
rescue Gem::LoadError
puts "Gem #{name} not found, trying to install..."
require 'rubygems/commands/install_command'
args = ["--no-ri", "--no-rdoc", name]
args.concat(['--version', version]) if version
Gem::Commands::InstallCommand.new.tap do |c|
c.handle_options(args)
begin
c.execute
rescue Gem::SystemExitException
end
end
require name
end
@nilsding
Copy link

nilsding commented Aug 5, 2016

What about gems which have a different name than the one that needs to be required? Take the awesome_print gem for example, older versions can only be required via require 'ap'

@zverok
Copy link
Author

zverok commented Aug 14, 2016

@nilsding Yeah, that is a problem (and Gist doesn't sending comment notifications is another one).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment