Created
October 13, 2022 10:21
-
-
Save thiagofm/6d854a2bd85d4348f5856167a21ee445 to your computer and use it in GitHub Desktop.
prepend
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
class Wheel | |
def tire | |
puts "Tire is flat, needs service" | |
end | |
end | |
Wheel.new.tire | |
# Tire is flat, needs service | |
module SpareTire | |
def tire | |
puts "Tire is on perfect working condtions" | |
end | |
end | |
Wheel.prepend(SpareTire).new.tire | |
# Tire is on perfect working condtions | |
# Prepend adds SpareTire to the beginning of | |
# Wheel's ancestors | |
Wheel.ancestors | |
# => [SpareTire, Wheel, Object, PP::ObjectMixin, Kernel, BasicObject] | |
# This means you override that method | |
# It can also be used to add Telemetry data to custom code you don't own 😌 | |
module TireTelemetry | |
def tire | |
puts "Here I started" | |
super # This will call the previous "tire" method | |
puts "Here I finished" | |
end | |
end | |
Wheel.prepend(TireTelemetry).new.tire | |
# Here I started | |
# Tire is on perfect working condtions | |
# Here I finished ✨ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment