| 1 | package AnyEvent::ZeroMQ::Subscribe::Trait::Topics; | ||
| 2 | BEGIN { | ||
| 3 | $AnyEvent::ZeroMQ::Subscribe::Trait::Topics::VERSION = '0.01'; | ||
| 4 | } | ||
| 5 | # ABSTRACT: trait to parse messages and extract the topic | ||
| 6 | use Moose::Role; | ||
| 7 | use true; | ||
| 8 | use namespace::autoclean; | ||
| 9 | |||
| 10 | requires '_topics_changed'; | ||
| 11 | requires '_call_callback'; # cb, item, rest -> cb, item, topic, rest | ||
| 12 | |||
| 13 | has 'topic_regex' => ( | ||
| 14 | reader => 'topic_regex', | ||
| 15 | isa => 'RegexpRef', | ||
| 16 | lazy_build => 1, | ||
| 17 | ); | ||
| 18 | |||
| 19 | after '_topics_changed' => sub { | ||
| 20 | my $self = shift; | ||
| 21 | $self->clear_topic_regex; | ||
| 22 | }; | ||
| 23 | |||
| 24 | sub _build_topic_regex { | ||
| 25 | my $self = shift; | ||
| 26 | my @prefixes = map { quotemeta } $self->topics->members; | ||
| 27 | my $prefixes = join '|', @prefixes; | ||
| 28 | return qr/^($prefixes)(.*)$/; | ||
| 29 | } | ||
| 30 | |||
| 31 | around '_call_callback' => sub { | ||
| 32 | my ($orig, $self, $cb, @rest) = @_; | ||
| 33 | $self->$orig( sub { | ||
| 34 | my ($self, $item, @rest) = @_; | ||
| 35 | my $tr = $self->topic_regex; | ||
| 36 | if(my ($topic, $item) = ($item =~ /$tr/)){ | ||
| 37 | $cb->($self, $item, $topic, @rest); | ||
| 38 | } | ||
| 39 | else { | ||
| 40 | # should not happen | ||
| 41 | $cb->($self, $item, undef, @rest); | ||
| 42 | } | ||
| 43 | }, @rest); | ||
| 44 | |||
| 45 | }; | ||
| 46 | |||
| 47 | __END__ |