MOOOOOOOOOOOOOOSE
[gitmo/Moose.git] / t / 031_mixin_example.t
1 #!/usr/bin/perl
2
3 use strict;
4 use warnings;
5
6 use Test::More tests => 5;
7 use SUPER;
8
9 BEGIN {
10     use_ok('Moose');
11 }
12
13 =pod
14
15 This test demonstrates how simple it is to create Scala Style 
16 Class Mixin Composition. Below is an example taken from the 
17 Scala web site's example section, and trancoded to Moose.
18
19 L<http://scala.epfl.ch/intro/mixin.html>
20
21 A class can only be used as a mixin in the definition of another 
22 class, if this other class extends a subclass of the superclass 
23 of the mixin. Since ColoredPoint3D extends Point3D and Point3D 
24 extends Point2D which is the superclass of ColoredPoint2D, the 
25 code above is well-formed.
26
27   class Point2D(xc: Int, yc: Int) {
28     val x = xc;
29     val y = yc;
30     override def toString() = "x = " + x + ", y = " + y;
31   }
32   
33   class ColoredPoint2D(u: Int, v: Int, c: String) extends Point2D(u, v) {
34     val color = c;
35     def setColor(newCol: String): Unit = color = newCol;
36     override def toString() = super.toString() + ", col = " + color;
37   }
38   
39   class Point3D(xc: Int, yc: Int, zc: Int) extends Point2D(xc, yc) {
40     val z = zc;
41     override def toString() = super.toString() + ", z = " + z;
42   }
43   
44   class ColoredPoint3D(xc: Int, yc: Int, zc: Int, col: String)
45         extends Point3D(xc, yc, zc)
46         with ColoredPoint2D(xc, yc, col);
47         
48   
49   Console.println(new ColoredPoint3D(1, 2, 3, "blue").toString())
50         
51   "x = 1, y = 2, z = 3, col = blue"
52   
53 =cut
54
55 {
56     package Point2D;
57     use Moose;
58     
59     has 'x' => (is => 'rw');
60     has 'y' => (is => 'rw');       
61     
62     sub to_string {
63         my $self = shift;
64         "x = " . $self->x . ", y = " . $self->y;
65     }
66     
67     package ColoredPoint2D;
68     use Moose;
69     
70     extends 'Point2D';
71     
72     has 'color' => (is => 'rw');    
73     
74     sub to_string {
75         my $self = shift;
76         $self->SUPER . ', col = ' . $self->color;
77     }
78     
79     package Point3D;
80     use Moose;
81     
82     extends 'Point2D';
83     
84     has 'z' => (is => 'rw');        
85
86     sub to_string {
87         my $self = shift;
88         $self->SUPER . ', z = ' . $self->z;
89     }
90     
91     package ColoredPoint3D;
92     use Moose;
93     
94     extends 'Point3D';    
95        with 'ColoredPoint2D';
96     
97 }
98
99 my $colored_point_3d = ColoredPoint3D->new(x => 1, y => 2, z => 3, color => 'blue');
100 isa_ok($colored_point_3d, 'ColoredPoint3D');
101 isa_ok($colored_point_3d, 'Point3D');
102 isa_ok($colored_point_3d, 'Point2D');
103
104 is($colored_point_3d->to_string(),
105    'x = 1, y = 2, z = 3, col = blue',
106    '... got the right toString method');
107