home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / lib / ruby / 1.8 / delegate.rb < prev    next >
Encoding:
Ruby Source  |  2007-03-07  |  8.5 KB  |  335 lines

  1. # = delegate -- Support for the Delegation Pattern
  2. #
  3. # Documentation by James Edward Gray II and Gavin Sinclair
  4. #
  5. # == Introduction
  6. #
  7. # This library provides three different ways to delegate method calls to an
  8. # object.  The easiest to use is SimpleDelegator.  Pass an object to the
  9. # constructor and all methods supported by the object will be delegated.  This
  10. # object can be changed later.
  11. #
  12. # Going a step further, the top level DelegateClass method allows you to easily
  13. # setup delegation through class inheritance.  This is considerably more
  14. # flexible and thus probably the most common use for this library.
  15. #
  16. # Finally, if you need full control over the delegation scheme, you can inherit
  17. # from the abstract class Delegator and customize as needed.  (If you find
  18. # yourself needing this control, have a look at _forwardable_, also in the
  19. # standard library.  It may suit your needs better.)
  20. #
  21. # == Notes
  22. #
  23. # Be advised, RDoc will not detect delegated methods.
  24. #
  25. # <b>delegate.rb provides full-class delegation via the
  26. # DelegateClass() method.  For single-method delegation via
  27. # def_delegator(), see forwardable.rb.</b>
  28. #
  29. # == Examples
  30. #
  31. # === SimpleDelegator
  32. #
  33. # Here's a simple example that takes advantage of the fact that
  34. # SimpleDelegator's delegation object can be changed at any time.
  35. #
  36. #   class Stats
  37. #     def initialize
  38. #       @source = SimpleDelegator.new([])
  39. #     end
  40. #     
  41. #     def stats( records )
  42. #       @source.__setobj__(records)
  43. #           
  44. #       "Elements:  #{@source.size}\n" +
  45. #       " Non-Nil:  #{@source.compact.size}\n" +
  46. #       "  Unique:  #{@source.uniq.size}\n"
  47. #     end
  48. #   end
  49. #   
  50. #   s = Stats.new
  51. #   puts s.stats(%w{James Edward Gray II})
  52. #   puts
  53. #   puts s.stats([1, 2, 3, nil, 4, 5, 1, 2])
  54. #
  55. # <i>Prints:</i>
  56. #
  57. #   Elements:  4
  58. #    Non-Nil:  4
  59. #     Unique:  4
  60. #   Elements:  8
  61. #    Non-Nil:  7
  62. #     Unique:  6
  63. #
  64. # === DelegateClass()
  65. #
  66. # Here's a sample of use from <i>tempfile.rb</i>.
  67. #
  68. # A _Tempfile_ object is really just a _File_ object with a few special rules
  69. # about storage location and/or when the File should be deleted.  That makes for
  70. # an almost textbook perfect example of how to use delegation.
  71. #
  72. #   class Tempfile < DelegateClass(File)
  73. #     # constant and class member data initialization...
  74. #   
  75. #     def initialize(basename, tmpdir=Dir::tmpdir)
  76. #       # build up file path/name in var tmpname...
  77. #     
  78. #       @tmpfile = File.open(tmpname, File::RDWR|File::CREAT|File::EXCL, 0600)
  79. #     
  80. #       # ...
  81. #     
  82. #       super(@tmpfile)
  83. #     
  84. #       # below this point, all methods of File are supported...
  85. #     end
  86. #   
  87. #     # ...
  88. #   end
  89. #
  90. # === Delegator
  91. #
  92. # SimpleDelegator's implementation serves as a nice example here.
  93. #
  94. #    class SimpleDelegator < Delegator
  95. #      def initialize(obj)
  96. #        super             # pass obj to Delegator constructor, required
  97. #        @_sd_obj = obj    # store obj for future use
  98. #      end
  99. #      def __getobj__
  100. #        @_sd_obj          # return object we are delegating to, required
  101. #      end
  102. #      def __setobj__(obj)
  103. #        @_sd_obj = obj    # change delegation object, a feature we're providing
  104. #      end
  105. #      # ...
  106. #    end
  107.  
  108. #
  109. # Delegator is an abstract class used to build delegator pattern objects from
  110. # subclasses.  Subclasses should redefine \_\_getobj\_\_.  For a concrete
  111. # implementation, see SimpleDelegator.
  112. #
  113. class Delegator
  114.  
  115.   #
  116.   # Pass in the _obj_ to delegate method calls to.  All methods supported by
  117.   # _obj_ will be delegated to.
  118.   #
  119.   def initialize(obj)
  120.     preserved = ::Kernel.public_instance_methods(false)
  121.     preserved -= ["to_s","to_a","inspect","==","=~","==="]
  122.     for t in self.class.ancestors
  123.       preserved |= t.public_instance_methods(false)
  124.       preserved |= t.private_instance_methods(false)
  125.       preserved |= t.protected_instance_methods(false)
  126.       break if t == Delegator
  127.     end
  128.     preserved << "singleton_method_added"
  129.     for method in obj.methods
  130.       next if preserved.include? method
  131.       begin
  132.     eval <<-EOS
  133.       def self.#{method}(*args, &block)
  134.         begin
  135.           __getobj__.__send__(:#{method}, *args, &block)
  136.         rescue Exception
  137.           $@.delete_if{|s| /:in `__getobj__'$/ =~ s} #`
  138.           $@.delete_if{|s| /^\\(eval\\):/ =~ s}
  139.           ::Kernel::raise
  140.         end
  141.       end
  142.     EOS
  143.       rescue SyntaxError
  144.         raise NameError, "invalid identifier %s" % method, caller(4)
  145.       end
  146.     end
  147.   end
  148.   alias initialize_methods initialize
  149.  
  150.   # Handles the magic of delegation through \_\_getobj\_\_.
  151.   def method_missing(m, *args)
  152.     target = self.__getobj__
  153.     unless target.respond_to?(m)
  154.       super(m, *args)
  155.     end
  156.     target.__send__(m, *args)
  157.   end
  158.  
  159.   # 
  160.   # Checks for a method provided by this the delegate object by fowarding the 
  161.   # call through \_\_getobj\_\_.
  162.   # 
  163.   def respond_to?(m)
  164.     return true if super
  165.     return self.__getobj__.respond_to?(m)
  166.   end
  167.  
  168.   #
  169.   # This method must be overridden by subclasses and should return the object
  170.   # method calls are being delegated to.
  171.   #
  172.   def __getobj__
  173.     raise NotImplementedError, "need to define `__getobj__'"
  174.   end
  175.  
  176.   # Serialization support for the object returned by \_\_getobj\_\_.
  177.   def marshal_dump
  178.     __getobj__
  179.   end
  180.   # Reinitializes delegation from a serialized object.
  181.   def marshal_load(obj)
  182.     initialize_methods(obj)
  183.   end
  184. end
  185.  
  186. #
  187. # A concrete implementation of Delegator, this class provides the means to
  188. # delegate all supported method calls to the object passed into the constructor
  189. # and even to change the object being delegated to at a later time with
  190. # \_\_setobj\_\_ .
  191. #
  192. class SimpleDelegator<Delegator
  193.  
  194.   # Pass in the _obj_ you would like to delegate method calls to.
  195.   def initialize(obj)
  196.     super
  197.     @_sd_obj = obj
  198.   end
  199.  
  200.   # Returns the current object method calls are being delegated to.
  201.   def __getobj__
  202.     @_sd_obj
  203.   end
  204.  
  205.   #
  206.   # Changes the delegate object to _obj_.
  207.   #
  208.   # It's important to note that this does *not* cause SimpleDelegator's methods
  209.   # to change.  Because of this, you probably only want to change delegation
  210.   # to objects of the same type as the original delegate.
  211.   #
  212.   # Here's an example of changing the delegation object.
  213.   #
  214.   #   names = SimpleDelegator.new(%w{James Edward Gray II})
  215.   #   puts names[1]    # => Edward
  216.   #   names.__setobj__(%w{Gavin Sinclair})
  217.   #   puts names[1]    # => Sinclair
  218.   #
  219.   def __setobj__(obj)
  220.     raise ArgumentError, "cannot delegate to self" if self.equal?(obj)
  221.     @_sd_obj = obj
  222.   end
  223.  
  224.   # Clone support for the object returned by \_\_getobj\_\_.
  225.   def clone
  226.     super
  227.     __setobj__(__getobj__.clone)
  228.   end
  229.   # Duplication support for the object returned by \_\_getobj\_\_.
  230.   def dup(obj)
  231.     super
  232.     __setobj__(__getobj__.dup)
  233.   end
  234. end
  235.  
  236. # :stopdoc:
  237. # backward compatibility ^_^;;;
  238. Delegater = Delegator
  239. SimpleDelegater = SimpleDelegator
  240. # :startdoc:
  241.  
  242. #
  243. # The primary interface to this library.  Use to setup delegation when defining
  244. # your class.
  245. #
  246. #   class MyClass < DelegateClass( ClassToDelegateTo )    # Step 1
  247. #     def initiaize
  248. #       super(obj_of_ClassToDelegateTo)                   # Step 2
  249. #     end
  250. #   end
  251. #
  252. def DelegateClass(superclass)
  253.   klass = Class.new
  254.   methods = superclass.public_instance_methods(true)
  255.   methods -= ::Kernel.public_instance_methods(false)
  256.   methods |= ["to_s","to_a","inspect","==","=~","==="]
  257.   klass.module_eval {
  258.     def initialize(obj)  # :nodoc:
  259.       @_dc_obj = obj
  260.     end
  261.     def method_missing(m, *args)  # :nodoc:
  262.       unless @_dc_obj.respond_to?(m)
  263.         super(m, *args)
  264.       end
  265.       @_dc_obj.__send__(m, *args)
  266.     end
  267.     def respond_to?(m)  # :nodoc:
  268.       return true if super
  269.       return @_dc_obj.respond_to?(m)
  270.     end
  271.     def __getobj__  # :nodoc:
  272.       @_dc_obj
  273.     end
  274.     def __setobj__(obj)  # :nodoc:
  275.       raise ArgumentError, "cannot delegate to self" if self.equal?(obj)
  276.       @_dc_obj = obj
  277.     end
  278.     def clone  # :nodoc:
  279.       super
  280.       __setobj__(__getobj__.clone)
  281.     end
  282.     def dup  # :nodoc:
  283.       super
  284.       __setobj__(__getobj__.dup)
  285.     end
  286.   }
  287.   for method in methods
  288.     begin
  289.       klass.module_eval <<-EOS, __FILE__, __LINE__+1
  290.         def #{method}(*args, &block)
  291.       begin
  292.         @_dc_obj.__send__(:#{method}, *args, &block)
  293.       rescue
  294.         $@[0,2] = nil
  295.         raise
  296.       end
  297.     end
  298.       EOS
  299.     rescue SyntaxError
  300.       raise NameError, "invalid identifier %s" % method, caller(3)
  301.     end
  302.   end
  303.   return klass
  304. end
  305.  
  306. # :enddoc:
  307.  
  308. if __FILE__ == $0
  309.   class ExtArray<DelegateClass(Array)
  310.     def initialize()
  311.       super([])
  312.     end
  313.   end
  314.  
  315.   ary = ExtArray.new
  316.   p ary.class
  317.   ary.push 25
  318.   p ary
  319.  
  320.   foo = Object.new
  321.   def foo.test
  322.     25
  323.   end
  324.   def foo.error
  325.     raise 'this is OK'
  326.   end
  327.   foo2 = SimpleDelegator.new(foo)
  328.   p foo.test == foo2.test    # => true
  329.   foo2.error            # raise error!
  330. end
  331.