Added apply_if to only run an apply block if a predicate is true
Oliver Charles [Fri, 28 Jan 2011 15:33:55 +0000 (15:33 +0000)]
lib/HTML/Zoom.pm
lib/HTML/Zoom/StreamBase.pm
t/apply.t [new file with mode: 0644]

index dba35d3..80ee8e9 100644 (file)
@@ -78,6 +78,17 @@ sub apply {
   $self->$code;
 }
 
+sub apply_if {
+  my ($self, $predicate, $code) = @_;
+  if($predicate) {
+    local $_ = $self;
+    $self->$code;
+  }
+  else {
+    $self;
+  }
+}
+
 sub to_html {
   my $self = shift;
   $self->zconfig->producer->html_from_stream($self->to_stream);
index 6c0b416..e063c48 100644 (file)
@@ -83,6 +83,17 @@ sub apply {
   $self->$code;
 }
 
+sub apply_if {
+  my ($self, $predicate, $code) = @_;
+  if($predicate) {
+    local $_ = $self;
+    $self->$code;
+  }
+  else {
+    $self;
+  }
+}
+
 sub to_html {
   my ($self) = @_;
   $self->_zconfig->producer->html_from_stream($self);
diff --git a/t/apply.t b/t/apply.t
new file mode 100644 (file)
index 0000000..4071ff4
--- /dev/null
+++ b/t/apply.t
@@ -0,0 +1,31 @@
+use strict;
+use warnings FATAL => 'all';
+use Test::More 'no_plan';
+
+use HTML::Zoom;
+
+my $template = <<HTML;
+<html>
+  <body></body>
+</html>
+HTML
+
+my $expect = <<HTML;
+<html>
+  <body>Hello</body>
+</html>
+HTML
+
+my $output = HTML::Zoom
+  ->from_html($template)
+  ->apply_if(1, sub { $_->select('body')->replace_content('Hello') })
+  ->to_html;
+
+is( $output => $expect, 'apply_if with a true predicate' );
+
+$output = HTML::Zoom
+  ->from_html($template)
+  ->apply_if(0, sub { $_->select('body')->replace_content('Hello') })
+  ->to_html;
+
+is( $output => $template, 'apply_if with a false predicate' );