Skip to content

Instantly share code, notes, and snippets.

@nicomen
Last active June 22, 2016 11:37
Show Gist options
  • Save nicomen/676a315d47006f40e6ca81ec76cab0bd to your computer and use it in GitHub Desktop.
Save nicomen/676a315d47006f40e6ca81ec76cab0bd to your computer and use it in GitHub Desktop.
package Around;
use Mojo::Util qw/trim/;
use Moose;
has "trimmed" => (is => 'rw', isa => 'Str');
around "trimmed" => sub {
my ($orig, $self, $str) = @_;
if (scalar @_ > 2) {
return $self->$orig( defined $str ? trim $str : $str );
}
return trim $self->$orig;
};
package AroundSimple;
use Mojo::Util qw/trim/;
use Moose;
has "trimmed" => (is => 'rw', isa => 'Str');
around "trimmed" => sub {
my ($orig, $self, $str) = @_;
return (scalar @_ > 2) ? $self->$orig( $str ) : trim $self->$orig;
};
package Coerced;
use Mojo::Util qw/trim/;
use Moose;
use Moose::Util::TypeConstraints;
subtype 'TrimmedStr',
as 'Str',
where { $_ !~ /(^\s|\s$)/ };
coerce 'TrimmedStr',
from 'Str',
via { defined $_ ? trim $_ : $_ };
has "trimmed" => (is => "rw", isa => "TrimmedStr", coerce => 1);
package main;
use v5.10;
my $a = Around->new( trimmed => " haha " );
say join $a->trimmed, qw/" "/;
my $s = AroundSimple->new( trimmed => " haha " );
say join $s->trimmed, qw/" "/;
my $c = Coerced->new( trimmed => " haha " );
say join $c->trimmed, qw/" "/;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment