Lets play with decorators
This file contains 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
require "delegate" | |
class A | |
def self.class_meth | |
"class method" | |
end | |
def self.class_meth_with_args a, b | |
"class method args: " + a + b | |
end | |
def meth | |
"instance method" | |
end | |
end | |
# | |
#It works! | |
module DelegateWholeClass | |
#borrowed from Delegate.delegating_block | |
def self.delegate_block(mid, target) | |
lambda do |*args, &block| | |
begin | |
target.__send__(mid, *args, &block) | |
ensure | |
$@.delete_if {|t| /\A#{Regexp.quote(__FILE__)}:#{__LINE__-2}:/ =~ t} if $@ | |
end | |
end | |
end | |
end | |
def DelegateWholeClass(superclass) | |
klass = DelegateClass(superclass) | |
klass_methods = superclass.public_methods - klass.public_methods | |
klass_methods.each do |meth| | |
klass.define_singleton_method(meth,DelegateWholeClass.delegate_block(meth, superclass)) | |
end | |
klass | |
end | |
class T < DelegateWholeClass(A) | |
def meth | |
super + "<- from A" | |
end | |
def t_meth | |
"T:" + meth | |
end | |
def self.t_class_meth | |
"T class meth" | |
end | |
def self.class_meth | |
super + "<- from A" | |
end | |
end | |
t = T.new A.new | |
puts t.meth | |
puts T.class_meth | |
puts T.class_meth_with_args "bla," , 1.to_s | |
puts t.t_meth | |
puts T.t_class_meth |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment