[rt.cpan.org 36863]
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / CDBICompat / AccessorMapping.pm
1 package # hide from PAUSE Indexer
2   DBIx::Class::CDBICompat::AccessorMapping;
3
4 use strict;
5 use warnings;
6
7 sub mk_group_accessors {
8     my ($class, $group, @cols) = @_;
9
10     foreach my $col (@cols) {
11         my($accessor, $col) = ref $col ? @$col : (undef, $col);
12
13         my($ro_meth, $wo_meth);
14         if( defined $accessor ) {
15             $ro_meth = $wo_meth = $accessor;
16         }
17         else {
18             $ro_meth = $class->accessor_name_for($col);
19             $wo_meth = $class->mutator_name_for($col);
20         }
21
22         # warn "class: $class / col: $col / ro: $ro_meth / wo: $wo_meth\n";
23         if ($ro_meth eq $wo_meth or # they're the same
24               $wo_meth eq $col)     # or only the accessor is custom
25           {
26               $class->next::method($group => [ $ro_meth => $col ]);
27           } else {
28               $class->mk_group_ro_accessors($group => [ $ro_meth => $col ]);
29               $class->mk_group_wo_accessors($group => [ $wo_meth => $col ]);
30           }
31     }
32 }
33
34
35 sub accessor_name_for {
36     my ($class, $column) = @_;
37     if ($class->can('accessor_name')) { 
38         return $class->accessor_name($column) 
39     }
40
41     return $column;
42 }
43
44 sub mutator_name_for {
45     my ($class, $column) = @_;
46     if ($class->can('mutator_name')) { 
47         return $class->mutator_name($column) 
48     }
49
50     return $column;
51 }
52
53
54 sub new {
55     my ($class, $attrs, @rest) = @_;
56     $class->throw_exception( "create needs a hashref" ) unless ref $attrs eq 'HASH';
57     foreach my $col ($class->columns) {
58         my $acc = $class->accessor_name_for($col);
59         $attrs->{$col} = delete $attrs->{$acc} if exists $attrs->{$acc};
60
61         my $mut = $class->mutator_name_for($col);
62         $attrs->{$col} = delete $attrs->{$mut} if exists $attrs->{$mut};
63     }
64     return $class->next::method($attrs, @rest);
65 }
66
67 1;