basic structure in place
[dbsrgits/DBIx-Class-ResultSet-WithMetaData.git] / lib / DBIx / Class / ResultSet / WithMetaData.pm
1 package DBIx::Class::ResultSet::WithMetaData;
2
3 use strict;
4 use warnings;
5
6 use Data::Alias;
7 use Moose;
8 use MooseX::Method::Signatures;
9 extends 'DBIx::Class::ResultSet';
10
11 has '_row_info' => (
12         is => 'rw',
13         isa => 'HashRef'
14 );
15
16 has 'was_row' => (
17         is => 'rw',
18         isa => 'Int'
19 );
20
21 sub new {
22         my $self = shift;
23   my $new = $self->next::method(@_);
24         foreach my $key (qw/_row_info/) {
25                 alias $new->{$key} = $new->{attrs}{$key};
26                 $new->{$key} = {} unless $new->{$key};
27         }
28
29         return $new;
30 }
31
32 method with_token {
33         foreach my $row ($self->all) {
34                 my $token = $self->tokenify($row->get_column($self->token_col));
35                 $self->add_row_info(id => $row->id, info => { join('_', 'token', $self->token_col) => $token });
36         }
37
38         return $self;
39 }
40
41 method display () {
42   my $rs = $self->search({});
43   $rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
44   my @rows;
45         foreach my $row ($rs->all) {
46                 if (my $info = $self->row_info_for(id => $row->{id})) {
47                         $row = { %{$row}, %{$info} };
48                 }
49                 push(@rows, $row);
50         }
51
52   return ($self->was_row) ? $rows[0] : \@rows;
53 }
54
55 method add_row_info (Int :$id, HashRef :$info) {
56         unless ($self->find($id)) {
57                 warn $id;
58                 die 'invalid id passed to add_row_info';
59         }
60
61         if (my $existing = $self->_row_info->{$id}) {
62                 $info = { %{$existing}, %{$info} };
63         }
64
65         $self->_row_info->{$id} = $info;        
66 }
67
68 method row_info_for (Int :$id) {
69         return $self->_row_info->{$id};
70 }
71
72 method order_by (Str :$col) {
73         $col = "me.$col" unless ($col =~ m/\./);
74         return $self->search({}, { order_by => $col });
75 }
76
77 method limit (Int :$count) {
78         return $self->search({}, { rows => $count });
79 }
80
81 sub tokenify {
82   my ($self, $string) = @_;
83
84   $string =~ s/\s+$//;
85   $string =~ s/[,\.\-\+]//g;
86   $string =~ s/^\s+//;
87   $string =~ s/ /-/g;
88   $string = lc($string);
89   return $string;
90 }
91
92 sub clean_rs {
93   my $self = shift;
94
95   return $self->result_source->resultset;
96 }
97
98 1;