Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
improved tap method in Mojo::Base to be able to call methods
  • Loading branch information
kraih committed Nov 2, 2014
1 parent 25b4237 commit b46d507
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 2 deletions.
1 change: 1 addition & 0 deletions Changes
Expand Up @@ -4,6 +4,7 @@
- Deprecated Mojo::Collection::pluck in favor of Mojo::Collection::map.
- Deprecated Mojo::DOM::val.
- Improved map method in Mojo::Collection to be able to call methods.
- Improved tap method in Mojo::Base to be able to call methods.

5.56 2014-10-29
- Deprecated Mojo::Collection::AUTOLOAD in favor of Mojo::Collection::pluck.
Expand Down
9 changes: 7 additions & 2 deletions lib/Mojo/Base.pm
Expand Up @@ -84,8 +84,8 @@ sub new {
}

sub tap {
my ($self, $cb) = @_;
$_->$cb for $self;
my ($self, $cb) = (shift, shift);
$_->$cb(@_) for $self;
return $self;
}

Expand Down Expand Up @@ -209,11 +209,16 @@ pass it either a hash or a hash reference with attribute values.
=head2 tap
$object = $object->tap(sub {...});
$object = $object->tap($method);
$object = $object->tap($method, @args);
K combinator, tap into a method chain to perform operations on an object
within the chain. The object will be the first argument passed to the callback
and is also available as C<$_>.
# Longer version
$object = $object->tap(sub { $_->$method(@args) });
=head1 DEBUGGING
You can set the C<MOJO_BASE_DEBUG> environment variable to get some advanced
Expand Down
5 changes: 5 additions & 0 deletions t/mojo/base.t
Expand Up @@ -13,6 +13,8 @@ use base 'Mojo::BaseTest::Base2';
__PACKAGE__->attr(heads => 1);
__PACKAGE__->attr('name');

sub more_heads { shift->{heads} += shift // 1 }

package Mojo::BaseTestTest;
use Mojo::Base 'Mojo::BaseTest';

Expand Down Expand Up @@ -66,6 +68,9 @@ $monkey = Mojo::BaseTest->new;
is $monkey->tap(sub { $_->name('foo') })->name, 'foo', 'right attribute value';
is $monkey->tap(sub { shift->name('bar')->name })->name, 'bar',
'right attribute value';
is $monkey->tap('heads')->heads, 1, 'right attribute value';
is $monkey->tap('more_heads')->heads, 2, 'right attribute value';
is $monkey->tap(more_heads => 3)->heads, 5, 'right attribute value';

# Inherit -base flag
$monkey = Mojo::BaseTest::Base3->new(evil => 1);
Expand Down

0 comments on commit b46d507

Please sign in to comment.