From: Oliver Charles Date: Fri, 28 Jan 2011 15:33:55 +0000 (+0000) Subject: Added apply_if to only run an apply block if a predicate is true X-Git-Tag: release_0.009004~9^2 X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=catagits%2FHTML-Zoom.git;a=commitdiff_plain;h=fdb039c6cede6d5cff55d27bde6afd723507cb81 Added apply_if to only run an apply block if a predicate is true --- diff --git a/lib/HTML/Zoom.pm b/lib/HTML/Zoom.pm index dba35d3..80ee8e9 100644 --- a/lib/HTML/Zoom.pm +++ b/lib/HTML/Zoom.pm @@ -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); diff --git a/lib/HTML/Zoom/StreamBase.pm b/lib/HTML/Zoom/StreamBase.pm index 6c0b416..e063c48 100644 --- a/lib/HTML/Zoom/StreamBase.pm +++ b/lib/HTML/Zoom/StreamBase.pm @@ -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 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 + +my $expect = < + Hello + +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' );