Last active
September 14, 2020 22:01
-
-
Save tobyink/d7af7070b53fcb9fe4660ba71708729a to your computer and use it in GitHub Desktop.
Example from the Zydeco pod, rewritten for Moo plus Type::Tiny
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
| use 5.008008; | |
| use strict; | |
| use warnings; | |
| { | |
| package MyApp; | |
| use parent 'Exporter::Tiny'; | |
| our @EXPORT_OK; | |
| { | |
| package MyApp::Types; | |
| use Type::Library -base; | |
| use Type::Tiny::Role; | |
| use Type::Tiny::Class; | |
| } | |
| { | |
| package MyApp::Person; | |
| 'MyApp::Types'->add_type( | |
| 'Type::Tiny::Class'->new( | |
| name => 'Person', | |
| class => 'MyApp::Person', | |
| ) | |
| ); | |
| use Moo; | |
| use Types::Standard qw( ClassName Str ); | |
| use Type::Params qw( compile compile_named_oo ); | |
| use namespace::autoclean; | |
| has 'name' => ( is => 'ro', isa => Str, required => 1 ); | |
| has 'gender' => ( is => 'ro', isa => Str ); | |
| my $check_for_new_man; | |
| sub MyApp::new_man { | |
| $check_for_new_man ||= compile( ClassName, Str ); | |
| my ( $factory, $name ) = &$check_for_new_man; | |
| return __PACKAGE__->new( name => $name, gender => 'male' ); | |
| } | |
| push @EXPORT_OK, qw( new_man ); | |
| sub MyApp::_generate_new_man { | |
| my $factory = shift; | |
| return sub { $factory->new_man( @_ ) }; | |
| } | |
| my $check_for_new_woman; | |
| sub MyApp::new_woman { | |
| $check_for_new_woman ||= compile( ClassName, Str ); | |
| my ( $factory, $name ) = &$check_for_new_woman; | |
| return __PACKAGE__->new( name => $name, gender => 'female' ); | |
| } | |
| push @EXPORT_OK, qw( new_woman ); | |
| sub MyApp::_generate_new_woman { | |
| my $factory = shift; | |
| return sub { $factory->new_woman( @_ ) }; | |
| } | |
| my $check_for_greet; | |
| sub greet { | |
| my $self = shift; | |
| $check_for_greet ||= compile_named_oo( | |
| 'friend' => 'MyApp::Types'->get_type('Person'), | |
| 'greeting' => Str, { default => 'Hello' }, | |
| ); | |
| my $arg = &$check_for_greet; | |
| printf( "%s, %s!\n", $arg->greeting, $arg->friend->name ); | |
| } | |
| sub from_string { | |
| my ( $class, $string ) = ( shift, @_ ); | |
| return $class->new( name => $string ); | |
| }; | |
| 'MyApp::Types'->get_type('Person')->coercion->add_type_coercions( | |
| Str, sub { __PACKAGE__->from_string( $_ ) }, | |
| ); | |
| } | |
| 'MyApp::Types'->make_immutable; | |
| } | |
| 'MyApp'->new_woman( 'Alice' )->greet( friend => 'Bob' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment