comments and caveats for applying overloads to instances
[gitmo/Role-Tiny.git] / t / overload.t
CommitLineData
9256ec21 1use strict;
2use warnings FATAL => 'all';
3use Test::More;
4
5BEGIN {
6 package MyRole;
7 use Role::Tiny;
8
9 sub as_string { "welp" }
10 sub as_num { 219 }
11 use overload
12 '""' => \&as_string,
13 '0+' => 'as_num',
c7260eec 14 bool => sub(){0},
9256ec21 15 fallback => 1;
16}
17
18BEGIN {
19 package MyClass;
20 use Role::Tiny::With;
21 with 'MyRole';
22 sub new { bless {}, shift }
23}
24
83a5e1e3 25BEGIN {
26 package MyClass2;
c7260eec 27 use overload
28 fallback => 0,
29 '""' => 'class_string',
30 '0+' => sub { 42 },
31 ;
83a5e1e3 32 use Role::Tiny::With;
33 with 'MyRole';
34 sub new { bless {}, shift }
c7260eec 35 sub class_string { 'yarp' }
83a5e1e3 36}
37
c7260eec 38{
39 my $o = MyClass->new;
40 is "$o", 'welp', 'subref overload';
41 is sprintf('%d', $o), 219, 'method name overload';
42 ok !$o, 'anon subref overload';
43}
9256ec21 44
c7260eec 45{
46 my $o = MyClass2->new;
47 eval { my $f = 0+$o };
48 like $@, qr/no method found/, 'fallback value not overwritten';
49 is "$o", 'yarp', 'method name overload not overwritten';
50 is sprintf('%d', $o), 42, 'subref overload not overwritten';
51}
83a5e1e3 52
9256ec21 53done_testing;