Newer Older
89 lines | 1.718kb
added Next version
Yuki Kimoto authored on 2011-11-16
1
package DBIx::Custom::Next::Order;
2
use Object::Simple -base;
3
use overload
4
  'bool'   => sub {1},
5
  '""'     => sub { shift->to_string },
6
  fallback => 1;
7

            
8
has 'dbi',
9
    orders => sub { [] };
10

            
11
sub prepend {
12
    my $self = shift;
13
    
14
    for my $order (reverse @_) {
15
        unshift @{$self->orders}, $order;
16
    }
17
    
18
    return $self;
19
}
20

            
21
sub to_string {
22
    my $self = shift;
23
    
24
    my $exists = {};
25
    my @orders;
26
    for my $order (@{$self->orders}) {
27
        next unless defined $order;
28
        $order =~ s/^\s+//;
29
        $order =~ s/\s+$//;
30
        my ($column, $direction) = split /\s+/, $order;
31
        push @orders, $order unless $exists->{$column};
32
        $exists->{$column} = 1;
33
    }
34
    
35
    return '' unless @orders;
36
    return 'order by ' . join(', ', @orders);
37
}
38

            
39
1;
40

            
41
=head1 NAME
42

            
43
DBIx::Custom::Next::Order - Order by
44

            
45
=head1 SYNOPSIS
46

            
47
    # Result
48
    my $order = DBIx::Custom::Next::Order->new;
49
    $order->prepend('title', 'author desc');
50
    my $order_by = "$order";
51
    
52
=head1 ATTRIBUTES
53

            
54
=head2 C<dbi>
55

            
56
    my $dbi = $order->dbi;
57
    $order = $order->dbi($dbi);
58

            
59
L<DBIx::Custom::Next> object.
60

            
61
=head2 C<orders>
62

            
63
    my $orders = $result->orders;
64
    $result = $result->orders(\%orders);
65

            
66
Parts of order by clause
67

            
68
=head1 METHODS
69

            
70
L<DBIx::Custom::Next::Result> inherits all methods from L<Object::Simple>
71
and implements the following new ones.
72

            
73
=head2 C<prepend>
74

            
75
    $order->prepend('title', 'author desc');
76

            
77
Prepend order parts to C<orders>.
78

            
79
=head2 C<to_string>
80

            
81
    my $order_by = $order->to_string;
82

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

            
86
    my $order_by = "$order";
87

            
88
=cut
89