Skip to content

Instantly share code, notes, and snippets.

@upgradeksh
Last active February 3, 2016 05:37
Show Gist options
  • Save upgradeksh/65f25d75239b9f51c18c to your computer and use it in GitHub Desktop.
Save upgradeksh/65f25d75239b9f51c18c to your computer and use it in GitHub Desktop.
Moo with Types::Standard and Type::Tiny::Class
#!/usr/bin/env perl
use feature qw(say);
use utf8;
use strict;
use warnings;
package A::B::C {
use Moo;
use Type::Tiny::Class;
use Types::Standard qw( Str Int ArrayRef HashRef );
my $DateTime = Type::Tiny::Class->new( class => 'DateTime' );
my $DICE = Type::Tiny->new(
name => 'DiceValue',
constraint => sub { 0 < $_ && $_ < 7 },
message => sub { "$_ is out of range, 1-6" },
);
has string => ( is => 'rw', isa => Str );
has number => ( is => 'rw', isa => Int );
has arrref => ( is => 'ro', isa => ArrayRef );
has hashref => ( is => 'ro', isa => HashRef );
has datetime => ( is => 'ro', isa => $DateTime );
has dice => ( is => 'ro', isa => $DICE );
}
package main {
use DateTime;
use Data::Printer;
my $dt = DateTime->now;
my $abc = A::B::C->new(
string => 'blah blah blah',
number => -1,
arrref => [ 1, 2, 3 ],
hashref => { a => 1, b => 2, },
datetime => $dt,
dice => 6,
);
p $abc;
say $abc->string;
say $abc->number;
say $abc->arrref;
say $abc->hashref;
say $abc->datetime;
say $abc->dice;
}
@upgradeksh
Copy link
Author

This gist shows how to make type of attributes strict.

  1. String
  2. Integer
  3. Array Reference
  4. Hash Reference
  5. Class
  6. User Defined

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment