in reply to Extending object you don't create

How about re-blessing?

Let HTML::TreeBuilder construct the tree, then re-bless instances of HTML::Element to be instances of your subclass (of HTML::Element).

Or, if you need to do this during construction, consider subclassing HTML::TreeBuilder and selectively overriding methods.

Replies are listed 'Best First'.
Re: Re: Extending object you don't create
by merlyn (Sage) on Feb 28, 2001 at 06:42 UTC
    Or, if you need to do this during construction, consider subclassing HTML::TreeBuilder and selectively overriding methods.
    That won't work if HTML::TreeBuilder has "hard coded" the name of HTML::Element, which I suspect it has.

    As a hack, I'd just define methods in HTML::Element's space.

    For long term, write the author of HTML::TreeBuilder and tell him to make the subclass an overrideable constant:

    package HTML::TreeBuilder; sub element_class { return "HTML::Element"; } ... sub make_sub_node { ... my $ele = $self->element_class->new(...); #makes an HTML::Element pe +rhaps .. }
    because then you can override that:
    package My::TreeBuilder; use base qw(HTML::TreeBuilder); sub element_class { return "My::Element" }; package My::Element; use base qw(HTML::Element); sub my_additional_method { ... }
    .

    -- Randal L. Schwartz, Perl hacker

      This is easier to pull off than that I thought. HTML::TreeBuilder already makes allowance for building a tree with objects other than instance of HTML::Element.
      my $tree = new HTML::TreeBuilder(...); # now replace 'HTML::Element' with my subclass $tree->{'_element_class'} = 'HTML::MyElementSubclass';

      Or, if this offends your sensibilities, subclass HTML::TreeBuilder, override new(), and invoke INHERITED::new() before resetting the element class.

      This works with HTML::TreeBuilder 3.09.

        Thanks. I didn't realize it had this ability. I will prostrate myself before the altar for a full day :)