Better linking in Relatiomship POD
[dbsrgits/DBIx-Class-Historic.git] / lib / DBIx / Class / Relationship / Accessor.pm
CommitLineData
75d07914 1package # hide from PAUSE
c0e7b4e5 2 DBIx::Class::Relationship::Accessor;
4a07648a 3
4use strict;
5use warnings;
ddc0a6c8 6use Sub::Name ();
7use Class::Inspector ();
4a07648a 8
71e65b39 9sub register_relationship {
10 my ($class, $rel, $info) = @_;
11 if (my $acc_type = $info->{attrs}{accessor}) {
223b8fe3 12 $class->add_relationship_accessor($rel => $acc_type);
4a07648a 13 }
71e65b39 14 $class->next::method($rel => $info);
4a07648a 15}
16
223b8fe3 17sub add_relationship_accessor {
4a07648a 18 my ($class, $rel, $acc_type) = @_;
19 my %meth;
20 if ($acc_type eq 'single') {
21 $meth{$rel} = sub {
22 my $self = shift;
23 if (@_) {
24 $self->set_from_related($rel, @_);
25 return $self->{_relationship_data}{$rel} = $_[0];
26 } elsif (exists $self->{_relationship_data}{$rel}) {
27 return $self->{_relationship_data}{$rel};
28 } else {
1a14aa3f 29 my $val = $self->find_related($rel, {}, {});
b28cc0ba 30 return unless $val;
31 return $self->{_relationship_data}{$rel} = $val;
4a07648a 32 }
33 };
34 } elsif ($acc_type eq 'filter') {
701da8c4 35 $class->throw_exception("No such column $rel to filter")
103647d5 36 unless $class->has_column($rel);
4685e006 37 my $f_class = $class->relationship_info($rel)->{class};
4a07648a 38 $class->inflate_column($rel,
39 { inflate => sub {
40 my ($val, $self) = @_;
e60dc79f 41 return $self->find_or_new_related($rel, {}, {});
4a07648a 42 },
43 deflate => sub {
44 my ($val, $self) = @_;
701da8c4 45 $self->throw_exception("$val isn't a $f_class") unless $val->isa($f_class);
4a07648a 46 return ($val->_ident_values)[0];
47 # WARNING: probably breaks for multi-pri sometimes. FIXME
48 }
49 }
50 );
51 } elsif ($acc_type eq 'multi') {
52 $meth{$rel} = sub { shift->search_related($rel, @_) };
5b89a768 53 $meth{"${rel}_rs"} = sub { shift->search_related_rs($rel, @_) };
4a07648a 54 $meth{"add_to_${rel}"} = sub { shift->create_related($rel, @_); };
55 } else {
701da8c4 56 $class->throw_exception("No such relationship accessor type $acc_type");
4a07648a 57 }
58 {
59 no strict 'refs';
60 no warnings 'redefine';
61 foreach my $meth (keys %meth) {
ddc0a6c8 62 my $name = join '::', $class, $meth;
63 *$name = Sub::Name::subname($name, $meth{$meth});
4a07648a 64 }
65 }
66}
67
681;