Skip to content

Instantly share code, notes, and snippets.

@bluefuton
Last active April 18, 2024 20:47
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bluefuton/5851093 to your computer and use it in GitHub Desktop.
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.
#!/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
@gasperhafner
Copy link

@bluefuton can it be done with passing arguments to make_noise_with_feeling method? Tnx!

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