/tools/Ruby/lib/ruby/1.8/rexml/child.rb

http://github.com/agross/netopenspace · Ruby · 96 lines · 42 code · 11 blank · 43 comment · 4 complexity · 2e3d90a5d29918e49cf3ea680c60315a MD5 · raw file

  1. require "rexml/node"
  2. module REXML
  3. ##
  4. # A Child object is something contained by a parent, and this class
  5. # contains methods to support that. Most user code will not use this
  6. # class directly.
  7. class Child
  8. include Node
  9. attr_reader :parent # The Parent of this object
  10. # Constructor. Any inheritors of this class should call super to make
  11. # sure this method is called.
  12. # parent::
  13. # if supplied, the parent of this child will be set to the
  14. # supplied value, and self will be added to the parent
  15. def initialize( parent = nil )
  16. @parent = nil
  17. # Declare @parent, but don't define it. The next line sets the
  18. # parent.
  19. parent.add( self ) if parent
  20. end
  21. # Replaces this object with another object. Basically, calls
  22. # Parent.replace_child
  23. #
  24. # Returns:: self
  25. def replace_with( child )
  26. @parent.replace_child( self, child )
  27. self
  28. end
  29. # Removes this child from the parent.
  30. #
  31. # Returns:: self
  32. def remove
  33. unless @parent.nil?
  34. @parent.delete self
  35. end
  36. self
  37. end
  38. # Sets the parent of this child to the supplied argument.
  39. #
  40. # other::
  41. # Must be a Parent object. If this object is the same object as the
  42. # existing parent of this child, no action is taken. Otherwise, this
  43. # child is removed from the current parent (if one exists), and is added
  44. # to the new parent.
  45. # Returns:: The parent added
  46. def parent=( other )
  47. return @parent if @parent == other
  48. @parent.delete self if defined? @parent and @parent
  49. @parent = other
  50. end
  51. alias :next_sibling :next_sibling_node
  52. alias :previous_sibling :previous_sibling_node
  53. # Sets the next sibling of this child. This can be used to insert a child
  54. # after some other child.
  55. # a = Element.new("a")
  56. # b = a.add_element("b")
  57. # c = Element.new("c")
  58. # b.next_sibling = c
  59. # # => <a><b/><c/></a>
  60. def next_sibling=( other )
  61. parent.insert_after self, other
  62. end
  63. # Sets the previous sibling of this child. This can be used to insert a
  64. # child before some other child.
  65. # a = Element.new("a")
  66. # b = a.add_element("b")
  67. # c = Element.new("c")
  68. # b.previous_sibling = c
  69. # # => <a><b/><c/></a>
  70. def previous_sibling=(other)
  71. parent.insert_before self, other
  72. end
  73. # Returns:: the document this child belongs to, or nil if this child
  74. # belongs to no document
  75. def document
  76. return parent.document unless parent.nil?
  77. nil
  78. end
  79. # This doesn't yet handle encodings
  80. def bytes
  81. encoding = document.encoding
  82. to_s
  83. end
  84. end
  85. end