Skip to content

Instantly share code, notes, and snippets.

@edenc
Created January 23, 2013 19:48
Show Gist options
  • Select an option

  • Save edenc/4612171 to your computer and use it in GitHub Desktop.

Select an option

Save edenc/4612171 to your computer and use it in GitHub Desktop.
use warnings;
use strict;
package Product;
use Moose;
has catalog => (
isa => 'Catalog',
is => 'ro',
required => 1,
handles => { is_discount_valid => 'validate_discount' }
);
has sku => ( isa => 'Int', is => 'ro', required => 1 );
has discount => ( isa => 'Int', is => 'ro', required => 1 );
has validated_discount => (
isa => 'Int',
is => 'ro',
lazy => 1,
builder => '_build_validated_discount'
);
sub _build_validated_discount {
my ($self) = @_;
my $disc = $self->discount;
return $self->is_discount_valid($disc) ? $disc : 0;
}
package Catalog;
use Moose;
has validator => ( isa => 'CodeRef', is => 'ro', required => 1 );
sub validate_discount {
my ( $self, $disc ) = @_;
return $self->validator->($disc);
}
sub create_product {
my ( $self, $sku, $discount ) = @_;
Product->new( sku => $sku, catalog => $self, discount => $discount );
}
package main;
my $cat1 = Catalog->new( validator => sub { shift() < 10 } );
my $cat2 = Catalog->new( validator => sub { shift() < 100 } );
my $sku = 1;
for my $set ( [ $cat1 => [qw(5 15)] ], [ $cat2 => [qw(5 15 200)] ] ) {
for my $disc ( @{ $set->[1] } ) {
my $prod = $set->[0]->create_product( $sku++, $disc );
print $prod->sku . ' - ' . $prod->validated_discount . "\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment