Last active
December 10, 2015 18:08
-
-
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
This file contains hidden or 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 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