Ruby: Saner way to redefine methods.
A better alias_method_chain? Depends on your tastes and needs, but having super is pretty nice…
class C
def foo() ‘f’ end
def bar() ‘b’ end
def foobar() foo + bar end
end
c = C.new
p c.foobar # => “fb”
class C
redefining do
def foo() super + ‘oo’ end
end
end
p c.foobar # => “foob”
class C
redefining do
def bar() super + ‘ar’ end
end
end
p c.foobar # => “foobar”
class C
redefining do
def foo() super.reverse end
def bar() super.reverse end
end
end
p c.foobar # => “oofrab”
class C
redef do
def foo() super.reverse end
def bar() super.reverse end
end
end
p c.foobar # => “foobar”
class C
redef do
def foobar() super.reverse end
end
end
p c.foobar # => “raboof”
class C
redef do
def foobar() super.reverse end
end
end
p c.foobar # => “foobar”
### the implementation: created by ara.t.howard and pit.capitain
BEGIN {
class Class
def redefined
singleton_class =
class « self
self
end
hash = Hash.new
singleton_class.module_eval{ define_method(:redefined){ hash } }
redefined
end
def redefining &block
include( redefined[:Module] ||= Module.new )
m = Module.new(&block)
methods = m.instance_methods(false) & instance_methods(false)
methods.each do |method|
redefined[method] = instance_method method
redefined[:Module].module_eval «-redefintion
def #{ method }(*a, &b)
self.class.redefined[‘#{ method }’].bind(self).call(*a, &b)
end
redefintion
remove_method method
end
include m
end
alias_method “redef”, “redefining”
end
}
def foo() ‘f’ end
def bar() ‘b’ end
def foobar() foo + bar end
end
c = C.new
p c.foobar # => “fb”
class C
redefining do
def foo() super + ‘oo’ end
end
end
p c.foobar # => “foob”
class C
redefining do
def bar() super + ‘ar’ end
end
end
p c.foobar # => “foobar”
class C
redefining do
def foo() super.reverse end
def bar() super.reverse end
end
end
p c.foobar # => “oofrab”
class C
redef do
def foo() super.reverse end
def bar() super.reverse end
end
end
p c.foobar # => “foobar”
class C
redef do
def foobar() super.reverse end
end
end
p c.foobar # => “raboof”
class C
redef do
def foobar() super.reverse end
end
end
p c.foobar # => “foobar”
### the implementation: created by ara.t.howard and pit.capitain
BEGIN {
class Class
def redefined
singleton_class =
class « self
self
end
hash = Hash.new
singleton_class.module_eval{ define_method(:redefined){ hash } }
redefined
end
def redefining &block
include( redefined[:Module] ||= Module.new )
m = Module.new(&block)
methods = m.instance_methods(false) & instance_methods(false)
methods.each do |method|
redefined[method] = instance_method method
redefined[:Module].module_eval «-redefintion
def #{ method }(*a, &b)
self.class.redefined[‘#{ method }’].bind(self).call(*a, &b)
end
redefintion
remove_method method
end
include m
end
alias_method “redef”, “redefining”
end
}
A gem perhaps?