Created
November 15, 2011 04:01
-
-
Save Getty/1366094 to your computer and use it in GitHub Desktop.
Testing concept for traits based on params
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env perl | |
| { | |
| package MyTest::Source::File; | |
| use Moose::Role; | |
| has filename => ( | |
| isa => 'Str', | |
| is => 'ro', | |
| required => 1, | |
| ); | |
| } | |
| { | |
| package MyTest::Source::DBIC; | |
| use Moose::Role; | |
| has schema => ( | |
| isa => 'DBIx::Class::Schema', | |
| is => 'ro', | |
| required => 1, | |
| ); | |
| } | |
| { | |
| package MyTest; | |
| use Moose; | |
| with 'MooseX::Traits'; | |
| use Data::Dumper; | |
| has source => ( | |
| is => 'ro', | |
| isa => 'Str', | |
| lazy_build => 1, | |
| ); | |
| sub _build_source { 'File' } | |
| around new => sub { | |
| my $orig = shift; | |
| my $class = shift; | |
| return $class->$orig(@_) if ref $_[0] eq 'HASH' and $_[0]->{_source_trait_added}; | |
| my $args = scalar @_ == 1 ? $_[0] : {@_}; | |
| my $source = defined $args->{source} ? $args->{source} : $class->_build_source; | |
| my $role = $class.'::Source::'.$source; | |
| $args->{_source_trait_added} = 1; | |
| $class->with_traits($role)->new($args); | |
| }; | |
| } | |
| my $test = MyTest->new( filename => 'bla' ); | |
| my $test2 = MyTest->new( source => 'DBIC' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment