Skip to content

Instantly share code, notes, and snippets.

@bachue
Last active December 10, 2015 18:08
Show Gist options
  • Save bachue/4472731 to your computer and use it in GitHub Desktop.
Save bachue/4472731 to your computer and use it in GitHub Desktop.
Finish a simple method alias, very easy implementation. super is also available in the block, it will call the same-name-method in superclass
class A
def f() 'This is OldA#f' end
end
puts A.new.f # => This is OldA#f
# ----------------
def alias_class_chain(cls, property, &block)
old_class_name = "#{cls.name}Without#{property}"
Object.send :const_set, old_class_name, cls
Object.send :remove_const, cls.name
Object.send :const_set, cls.name, Class.new(cls, &block)
end
alias_class_chain(A, 'Test') do
def f() 'This is NewA#f' end
end
puts A.new.f # => This is NewA#f
puts AWithoutTest.new.f #=> This is OldA#f
alias_class_chain(A, 'NewTest') do
def f() 'This is NewNewA#f' end
end
puts A.new.f # => This is NewNewA#f
puts AWithoutNewTest.new.f # => This is NewA#f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment