Last active
April 18, 2024 20:47
-
-
Save bluefuton/5851093 to your computer and use it in GitHub Desktop.
Quick example of how to override an instance method in an existing Ruby library. We use this approach when producing Redmine plugins.
This file contains 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
#!/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
@bluefuton can it be done with passing arguments to make_noise_with_feeling method? Tnx!