Permalink
Browse files

added event role

  • Loading branch information...
1 parent ddff2c8 commit 85aa77665659885f00a7d611d6b867548c1cd7e0 @jberger committed Jan 29, 2013
Showing with 63 additions and 0 deletions.
  1. +38 −0 lib/Moodule/Build/Role/Event.pm
  2. +25 −0 t/event.t
View
38 lib/Moodule/Build/Role/Event.pm
@@ -0,0 +1,38 @@
+package Moodule::Build::Role::Event;
+use Moo::Role;
+
+requires 'log_debug';
+
+has 'events' => (
+ is => 'rw',
+ default => sub { {} },
+);
+
+sub on_event {
+ my $self = shift;
+ my ($event, $method) = @_;
+ push @{$self->events->{$event}}, $method;
+}
+
+sub emit_event {
+ my $self = shift;
+ my ($event) = @_;
+ $self->log_debug( "Emitting: $event\n" );
+
+ my $methods = $self->events->{$event};
+ return undef unless defined $methods;
+
+ my $count = 0;
+ foreach my $method_name (@$methods) {
+ my $method = $self->can($method_name)
+ or die "Cannot find registered method $method_name (event: $event)";
+ $self->log_debug( "Triggering method: $method_name\n" );
+ $self->$method();
+ $count++;
+ }
+
+ return $count;
+}
+
+1;
+
View
25 t/event.t
@@ -0,0 +1,25 @@
+use strict;
+use warnings;
+
+use Test::More;
+
+my $method_output = 0;
+
+{
+ package MyTestClass;
+ use Moo;
+ with 'Moodule::Build::Role::Event';
+
+ sub log_debug { }
+ sub method1 { $method_output = 1 }
+}
+
+my $obj = MyTestClass->new;
+ok ! defined $obj->emit_event('myevent'), 'emit returns undef on undefined event';
+
+$obj->on_event( myevent => 'method1' );
+ok $obj->emit_event('myevent') == 1, 'emit returns number of events';
+ok $method_output == 1, 'event methods run';
+
+done_testing;
+

0 comments on commit 85aa776

Please sign in to comment.