Skip to content

Instantly share code, notes, and snippets.

@avdi
Created April 13, 2016 17:00
Show Gist options
  • Save avdi/892100c9d6485a497eda3aea4ff5e423 to your computer and use it in GitHub Desktop.
Save avdi/892100c9d6485a497eda3aea4ff5e423 to your computer and use it in GitHub Desktop.
Options for "soft" script dependencies
if Gem::Specification.find_all_by_name("clipboard", "~> 1.0").any?
gem "clipboard", "~> 1.0"
require "clipboard"
# ...
end
begin
gem "clipboard", "~> 1.0"
require "clipboard"
# ...
rescue LoadError
# NOOP
end
@avdi
Copy link
Author

avdi commented Apr 13, 2016

Note that both versions lock the version down to the 1.* range. I have a sense that the rescue.rb version, which I see most often, is largely cargo-culted from the pre-RubyGems era. But on the other hand, I might be missing something.

@drbrain
Copy link

drbrain commented Apr 13, 2016

I'd really hate to tell people to type all of line 1 of askrubygems.rb, but that's my only objection to it.

rescue.rb's flaw is line 5 and 6 that you have to add as boilerplate and can get wrong due to LoadError / Gem::LoadError typos or confusion (see PS below).

It seems like RubyGems should add a method that:

  • Returns a true-value if a gem with a version is installed (maybe specification?)
  • Returns false if a gem with a version is not installed
  • Activates the given version if it is installed

This would allow for the minimum typing:

if Gem.NAME_HERE 'clipboard', '~> 1.0
  require 'clipboard
  # …
end

PS: Line 5 of rescue.rb should be rescue Gem::LoadError.

You shouldn't need to rescue LoadError (as I'm sure you realize) as matching the gem name to the require name is a best practice already.

@drbrain
Copy link

drbrain commented Apr 13, 2016

In this instance the cargo cult built a functional airport.

You may be thinking of:

begin
  require 'rubygems'

  gem 'some_gem'
rescue LoadError, Gem::LoadError
end

require 'some_gem'

Which would allow you to load some_gem regardless of how it was installed.

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