class Delegator
def initialize(obj)
__setobj__(obj)
end
def __getobj__
raise NotImplementedError, "#{self.class}#__getobj__ is not implemented"
end
def __setobj__(_obj)
raise NotImplementedError, "#{self.class}#__setobj__ is not implemented"
end
def method_missing(m, *args, &block)
target = __getobj__
if target.respond_to?(m)
target.__send__(m, *args, &block)
else
super
end
end
def respond_to_missing?(m, include_private = false)
__getobj__.respond_to?(m, include_private) || super
end
def ==(other)
return true if other.equal?(self)
__getobj__ == other
end
def !=(other)
return false if other.equal?(self)
__getobj__ != other
end
def !
!__getobj__
end
def to_s
__getobj__.to_s
end
def inspect
__getobj__.inspect
end
end
class SimpleDelegator < Delegator
def __getobj__
@delegate_sd_obj
end
def __setobj__(obj)
@delegate_sd_obj = obj
end
end
DELEGATOR_NOT_DELEGATED = %i[
== != ! =~ !~ === <=> hash to_s inspect
is_a? kind_of? instance_of? class object_id __id__ equal?
respond_to? respond_to_missing? send public_send __send__
method methods public_methods private_methods protected_methods singleton_methods
instance_variable_get instance_variable_set instance_variables instance_variable_defined?
nil? frozen? freeze dup clone tap itself then yield_self display
define_singleton_method singleton_class extend instance_eval instance_exec
__getobj__ __setobj__ initialize method_missing marshal_dump marshal_load
].freeze
def DelegateClass(superklass, &block)
klass = Class.new(Delegator)
methods = superklass.public_instance_methods
methods -= DELEGATOR_NOT_DELEGATED
methods -= ::Delegator.public_instance_methods
klass.class_eval do
def __getobj__
@delegate_dc_obj
end
def __setobj__(obj)
@delegate_dc_obj = obj
end
methods.each do |method|
define_method(method) do |*args, &blk|
__getobj__.__send__(method, *args, &blk)
end
end
end
klass.class_eval(&block) if block
klass
end