Can I use an attribute modifer in Moose in a base class to handle multiple attributes from sub classes?

≡放荡痞女 提交于 2019-12-06 14:55:20

If you create a package like the one below, all you need in your classes is:

has date => (
   is     => 'rw',
   isa    => 'My::Date',
   coerce => 1,
);

Example code:

my $o = My::Class->new(date => '03 May 2012 12:33:42');
say $o->date();
say 0+$o->date();

$o->date(1336062822);
say $o->date();
say 0+$o->date();

The aforementioned module:

package My::Date;

use strict;
use warnings;

use Moose;
use Moose::Util::TypeConstraints;

use DateTime::Format::Strptime qw( );
use POSIX                      qw( strftime );

my $format = DateTime::Format::Strptime->new(
   pattern   => '%d %b %Y %H:%M:%S',
   locale    => 'en_US',
   time_zone => 'local',
   on_error  => 'croak',
);

has epoch => (
   is       => 'rw',
   isa      => 'Num',
   required => 1,
);

sub as_string {
   return strftime('%d %b %Y %H:%M:%S', localtime( $_[0]->epoch ));
}

coerce __PACKAGE__,
   from 'Num',
      via { __PACKAGE__->new( epoch => $_ ) },
   from 'Str',
      via { __PACKAGE__->new( epoch => $format->parse_datetime($_)->epoch ) };

use overload (
   '""' => sub { $_[0]->as_string },
   '0+' => sub { $_[0]->epoch },
   fallback => 1,
);

1;
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!