added new method to transform content
Andreas 'ac0v' Specht [Fri, 24 Jun 2011 00:07:05 +0000 (02:07 +0200)]
lib/HTML/Zoom/FilterBuilder.pm
t/actions.t

index 6040288..f9facd3 100644 (file)
@@ -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<HTML::Zoom> 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
index 4e3315b..b019db4 100644 (file)
@@ -150,6 +150,27 @@ is(
   'transform_attribute on nonexistent att does not add it if code returns undef',
   );
 
+($expect = $tmpl) =~ s{(</span>)}{ What ever$1}g;
+
+is(
+  ( run_for {
+      $_->transform_content( sub { "$_ What ever" } ),
+    } 'span'
+  ),
+  $expect,
+  'transform_content works for multiple selected elements',
+  );
+
+($expect = $tmpl) =~ s{(<span class="career">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/(?=<div)/O HAI/;