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