| 1 | package Dancer2::Plugin::ProbabilityRoute; | ||
| 2 | |||
| 3 | # ABSTRACT: plugin to define behavior with probability matching rules | ||
| 4 | |||
| 5 | |||
| 6 | use strict; | ||
| 7 | use warnings; | ||
| 8 | use Dancer2::Plugin; | ||
| 9 | use Digest::OAT 'oat'; | ||
| 10 | use Carp 'croak'; | ||
| 11 | |||
| 12 | my $_routes = {}; | ||
| 13 | |||
| 14 | |||
| 15 | register 'probability' => sub { | ||
| 16 | my ( $dsl, @routes ) = @_; | ||
| 17 | |||
| 18 | croak "Odd number of elements in routes" | ||
| 19 | if @routes % 2 != 0; | ||
| 20 | |||
| 21 | my $route_score = 0; | ||
| 22 | my @_probability_routes; | ||
| 23 | |||
| 24 | for ( my $i = 0; $i < @routes; $i += 2 ) { | ||
| 25 | my ( $probability, $code ) = ( $routes[$i], $routes[ $i + 1 ] ); | ||
| 26 | $route_score += $probability; | ||
| 27 | push @_probability_routes, [ $probability, $code ]; | ||
| 28 | } | ||
| 29 | |||
| 30 | if ( $route_score < 100 ) { | ||
| 31 | croak "Probability for route is lower than 100 ($route_score)"; | ||
| 32 | } | ||
| 33 | |||
| 34 | my $compiled_code = sub { | ||
| 35 | |||
| 36 | # we need a web context to execute that, so it cannot be moved | ||
| 37 | # out of the route's code | ||
| 38 | my $user_score; | ||
| 39 | if ( defined $dsl->session ) { | ||
| 40 | $user_score = oat( $dsl->session->id ) % 100; | ||
| 41 | } | ||
| 42 | |||
| 43 | my $probability_match = 0; | ||
| 44 | |||
| 45 | foreach my $route (@_probability_routes) { | ||
| 46 | my ( $probability, $code ) = (@$route); | ||
| 47 | $probability_match += $probability; | ||
| 48 | |||
| 49 | if ( $user_score < $probability_match ) { | ||
| 50 | return $code->(); | ||
| 51 | } | ||
| 52 | } | ||
| 53 | }; | ||
| 54 | }; | ||
| 55 | |||
| 56 | |||
| 57 | register probability_user_score => sub { | ||
| 58 | my $dsl = shift; | ||
| 59 | |||
| 60 | my $user_score; | ||
| 61 | if ( defined $dsl->session ) { | ||
| 62 | $user_score = oat( $dsl->session->id ) % 100; | ||
| 63 | } | ||
| 64 | return $user_score; | ||
| 65 | }; | ||
| 66 | |||
| 67 | register_plugin; | ||
| 68 | 1; | ||
| 69 | |||
| 70 | __END__ |