Created
March 25, 2014 15:33
-
-
Save outoftime/9764317 to your computer and use it in GitHub Desktop.
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
# | |
# Monkeypatching gem dependencies is a fact of life. But it's dangerous, because *any* update | |
# to a library might change internals that your patch depends on. This little snippet allows you | |
# to leave "reminders" in your code that you're relying on a particular version of a gem, and blows | |
# up if the gem loaded at runtime doesn't fit the requirement. | |
# | |
# Example: | |
# | |
# monkeypatch('awesome_lib', '1.2.2') do | |
# module AwesomeLib | |
# def awesome_method | |
# self.rely_on_internals_that_could_change_at_any_time(:cowboy => true) | |
# end | |
# end | |
# end | |
# | |
# Note that the `version_requirement` can be any version specification that RubyGems | |
# accepts, but if you're relying on any sort of internals in your monkeypatch, you'll | |
# want to specify an exact version. | |
# | |
def monkeypatch(name, version_requirement) | |
loaded_gem = Gem.loaded_specs[name] | |
raise LoadError, "Monkeypatched gem #{name} is not loaded" unless loaded_gem.present? | |
unless Gem::Requirement.new(version_requirement).satisfied_by?(loaded_gem.version) | |
raise LoadError, "Monkeypatch targets #{name} #{version_requirement}; " \ | |
"runtime version is #{loaded_gem.version.to_s}. Confirm that monkeypatch works " \ | |
"with this version and bump monkeypatch version requirement." | |
end | |
yield | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment