Created
April 13, 2016 17:00
-
-
Save avdi/892100c9d6485a497eda3aea4ff5e423 to your computer and use it in GitHub Desktop.
Options for "soft" script dependencies
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if Gem::Specification.find_all_by_name("clipboard", "~> 1.0").any? | |
gem "clipboard", "~> 1.0" | |
require "clipboard" | |
# ... | |
end | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
begin | |
gem "clipboard", "~> 1.0" | |
require "clipboard" | |
# ... | |
rescue LoadError | |
# NOOP | |
end |
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.
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
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.