From: Andreas 'ac0v' Specht Date: Fri, 24 Jun 2011 00:07:05 +0000 (+0200) Subject: added new method to transform content X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=cd1ced5dcb0ff77bb221c1cba0288789a7c03042;p=catagits%2FHTML-Zoom.git added new method to transform content --- diff --git a/lib/HTML/Zoom/FilterBuilder.pm b/lib/HTML/Zoom/FilterBuilder.pm index 6040288..f9facd3 100644 --- a/lib/HTML/Zoom/FilterBuilder.pm +++ b/lib/HTML/Zoom/FilterBuilder.pm @@ -128,6 +128,28 @@ sub transform_attribute { }; } +sub transform_content { + my ( $self, $code ) = @_; + + my $replace = $self->replace_content( + sub { + $self->_stream_from_proto($code->($_)); + } + ); + sub { + my ( $evt, $stream ) = @_; + + my $item_ref = $stream->next; + if ( $item_ref->{type} eq 'TEXT' ) { + local $_ = $item_ref->{raw}; + return $replace->($evt, $stream); + } + else { + return $self->_stream_concat($evt, $stream); + } + }; +} + sub collect { my ($self, $options) = @_; my ($into, $passthrough, $content, $filter, $flush_before) = @@ -690,6 +712,20 @@ or another L object. ->select('title, #greeting') ->replace_content('Hello world!'); +=head2 transform_content + +Given a "select" in HTML::Zoom result, transform the content with a code +reference. This allows you for example to localize your template text +elements or doing anything else with the node's text content. + + $html_zoom + ->select('a') + ->transform_content( + sub { + "please click on: $_" + }, + ); + =head2 repeat For a given selection, repeat over transformations, typically for the purposes diff --git a/t/actions.t b/t/actions.t index 4e3315b..b019db4 100644 --- a/t/actions.t +++ b/t/actions.t @@ -150,6 +150,27 @@ is( 'transform_attribute on nonexistent att does not add it if code returns undef', ); +($expect = $tmpl) =~ s{()}{ What ever$1}g; + +is( + ( run_for { + $_->transform_content( sub { "$_ What ever" } ), + } 'span' + ), + $expect, + 'transform_content works for multiple selected elements', + ); + +($expect = $tmpl) =~ s{(Builder)}{$1 What ever}; + +is( + ( run_for { + $_->transform_content( sub { "$_ What ever" } ), + } 'span.career' + ), + $expect, + 'transform_content works for one specific selected element', + ); ($expect = $tmpl) =~ s/(?=