Skip to content

Instantly share code, notes, and snippets.

@thiagofm
Created October 13, 2022 10:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thiagofm/6d854a2bd85d4348f5856167a21ee445 to your computer and use it in GitHub Desktop.
Save thiagofm/6d854a2bd85d4348f5856167a21ee445 to your computer and use it in GitHub Desktop.
prepend
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