File: 049-coercion-application-order.t

package info (click to toggle)
libmouse-perl 2.6.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,156 kB
  • sloc: perl: 14,569; ansic: 218; makefile: 8
file content (88 lines) | stat: -rw-r--r-- 2,097 bytes parent folder | download | duplicates (8)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 3;

# this tests that multiple type coercions on a given attribute get
# applied in the expected order.

{
    package Date;
    use Mouse;
    # This is just a simple class representing a date - in real life we'd use DateTime.

    has 'year' => 
        (is => 'rw',
         isa => 'Int');
    has 'month' => 
        (is => 'rw',
         isa => 'Int');
    has 'day' => 
        (is => 'rw',
         isa => 'Int');

    sub from_epoch
    {
        my $class = shift;
        my %d; @d{qw(year month day)} = (gmtime shift)[5,4,3];
        $d{year} += 1900;
        $d{month} += 1;
        Date->new(%d);
    }

    sub from_string
    {
        my $class = shift;
        my %d; @d{qw(year month day)} = split /\W/, shift;
        Date->new(%d);
    }


    sub to_string
    {
        my $self = shift;
        sprintf "%4d-%02d-%02d", 
            $self->year,
            $self->month,
            $self->day
    }

    package Event;
    use Mouse;
    use Mouse::Util::TypeConstraints;

    # These coercions must be applied in the right order - since a
    # number can be interpreted as a string, but not vice-versa, the
    # Int coercion should be applied first to get a correct answer.
    coerce 'Date' 
        => from 'Int' # a timestamp
            => via { Date->from_epoch($_) }

        => from 'Str' # <YYYY>-<MM>-<DD> 
            => via { Date->from_string($_) };



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

my $date = Date->new(year => 2001, month => 1, day => 1);
my $str = $date->to_string;
is $str, "2001-01-01", "initial date is correct: $str";

my $event = Event->new(date => $date);

$str = $event->date->to_string;
is $str, "2001-01-01", "initial date field correct: $str";

# check the order is applied correctly when given an Int
my $timestamp = 1238778317; # Fri Apr  3 17:05:17 2009
$event->date($timestamp);

$str = $event->date->to_string;
is $str, "2009-04-03", "coerced timestamp $timestamp to date field $str correctly";