Skip to content

Instantly share code, notes, and snippets.

@bradgessler
Last active February 8, 2024 03:07
Show Gist options
  • Save bradgessler/edc3af8ca2262633d6c8b05647844422 to your computer and use it in GitHub Desktop.
Save bradgessler/edc3af8ca2262633d6c8b05647844422 to your computer and use it in GitHub Desktop.
Upgrade a method in place
class Foo
# Define the original render method
def render
puts "Foo#render"
end
end
module Overrides
def self.prepended(klass)
klass.alias_method :base_render, :render
klass.include RenderMethods
klass.extend ClassMethods
end
module RenderMethods
# Define alternative versions of the render method
def render_1
base_render
puts "Version1#render"
end
def render_2
base_render
puts "Version2#render"
end
end
module ClassMethods
# Class method to switch render method implementations
def version=(version)
case version
when 1
# Alias render to render_1
self.alias_method :render, :render_1
when 2
# Alias render to render_2
self.alias_method :render, :render_2
else
raise ArgumentError, "Unknown render method version: #{version}"
end
end
end
end
class Foo
prepend Overrides
end
# Usage
foo = Foo.new
foo.render
puts "\nSwitching to Version 1"
Foo.version = 1
foo.render
puts "\nSwitching to Version 2"
Foo.version = 2
foo.render
puts "\nSwitching back to original"
Foo.version = 1
foo.render
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment