Skip to content

Instantly share code, notes, and snippets.

@bluefuton

bluefuton/lion_patch.rb

Last active Aug 22, 2019
Embed
What would you like to do?
Quick example of how to override an instance method in an existing Ruby library. We use this approach when producing Redmine plugins.
#!/usr/bin/env ruby -rubygems
module Zoo
module Animal
class Lion
def make_noise
"rawr"
end
end
end
end
lion = Zoo::Animal::Lion.new
puts 'Noise before patch: ' + lion.make_noise
# Patch the lion to make him purr
module LionPatch
def self.included(base)
base.send(:include, InstanceMethods)
base.class_eval do
alias_method :make_noise, :make_noise_with_feeling
end
end
module InstanceMethods
def make_noise_with_feeling
"purrrrr"
end
end
end
unless Zoo::Animal::Lion.included_modules.include? LionPatch
Zoo::Animal::Lion.send(:include, LionPatch)
end
lion_after_patch = Zoo::Animal::Lion.new
puts 'Noise after patch: ' + lion_after_patch.make_noise
# Expected output:
# Noise before patch: rawr
# Noise after patch: purrrrr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.