Top Level Namespace
Defined Under Namespace
Classes: Delegator, ExtArray, SimpleDelegator
Constant Summary collapse
- Delegater =
:stopdoc: backward compatibility ^_^;;;
Delegator- SimpleDelegater =
SimpleDelegator
Instance Method Summary collapse
-
#DelegateClass(superclass) ⇒ Object
The primary interface to this library.
Instance Method Details
#DelegateClass(superclass) ⇒ Object
The primary interface to this library. Use to setup delegation when defining your class.
class MyClass < DelegateClass( ClassToDelegateTo ) # Step 1
def initiaize
super(obj_of_ClassToDelegateTo) # Step 2
end
end
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 |
# File 'lib/delegate.rb', line 257 def DelegateClass(superclass) klass = Class.new methods = superclass.public_instance_methods(true) methods -= ::Kernel.public_instance_methods(false) methods |= ["to_s","to_a","inspect","==","=~","==="] klass.module_eval { def initialize(obj) # :nodoc: @_dc_obj = obj end def method_missing(m, *args) # :nodoc: unless @_dc_obj.respond_to?(m) super(m, *args) end @_dc_obj.__send__(m, *args) end def respond_to?(m) # :nodoc: return true if super return @_dc_obj.respond_to?(m) end def __getobj__ # :nodoc: @_dc_obj end def __setobj__(obj) # :nodoc: raise ArgumentError, "cannot delegate to self" if self.equal?(obj) @_dc_obj = obj end def clone # :nodoc: super __setobj__(__getobj__.clone) end def dup # :nodoc: super __setobj__(__getobj__.dup) end } for method in methods begin klass.module_eval <<-EOS def #{method}(*args, &block) begin @_dc_obj.__send__(:#{method}, *args, &block) rescue $@[0,2] = nil raise end end EOS rescue SyntaxError raise NameError, "invalid identifier %s" % method, caller(3) end end return klass end |