Newer Older
74 lines | 1.493kb
- added EXPERIMENTAL order m...
Yuki Kimoto authored on 2011-06-28
1
package DBIx::Custom::Order;
2
use Object::Simple -base;
3
use overload
4
  'bool'   => sub {1},
5
  '""'     => sub { shift->to_string },
6
  fallback => 1;
7

            
8
has orders => sub { [] };
9

            
10
sub prepend { unshift @{shift->orders}, @_ }
11

            
12
sub to_string {
13
    my $self = shift;
14
    
15
    my $exists = {};
16
    my @orders;
17
    foreach my $order (@{$self->orders}) {
18
        next unless defined $order;
19
        $order =~ s/^\s+//;
20
        $order =~ s/\s+$//;
21
        my ($column, $direction) = split /\s+/, $order;
22
        push @orders, $order unless $exists->{$column};
23
        $exists->{$column} = 1;
24
    }
25
    
26
    return '' unless @orders;
27
    return 'order by ' . join(', ', @orders);
28
}
29

            
30
1;
31

            
32
=head1 NAME
33

            
34
DBIx::Custom::Order - Order by EXPERIMENTAL
35

            
36
=head1 SYNOPSIS
37

            
38
    # Result
39
    my $order = DBIx::Custom::Order->new;
40
    $order->prepend('title', 'author desc');
41
    my $order_by = "$order";
42
    
43

            
44
=head1 ATTRIBUTES
45

            
46
=head2 C<orders>
47

            
48
    my $orders = $result->orders;
49
    $result = $result->orders(\%orders);
50

            
51
Parts of order by clause
52

            
53
=head1 METHODS
54

            
55
L<DBIx::Custom::Result> inherits all methods from L<Object::Simple>
56
and implements the following new ones.
57

            
58
=head2 C<prepend>
59

            
60
    $order->prepend('title', 'author desc');
61

            
62
Prepend order parts to C<orders>.
63

            
64
=head2 C<to_string>
65

            
66
    my $order_by = $order->to_string;
67

            
68
Create order by clause. If column name is duplicated, First one is used.
69
C<to_string> override stringification. so you can write the follwoing way.
70

            
71
    my $order_by = "$order";
72

            
73
=cut
74