X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=blobdiff_plain;f=lib%2FDBIx%2FClass%2FCDBICompat%2FHasA.pm;h=647674f1bd73454cfe62a84bc038e4952ca512cd;hb=fdb8385a961f14c3fd4ecf321c7ea6465066d306;hp=fe8521466a9ef2c25a66f7149e31f6ab614b0708;hpb=9f300b1bcbbaef6d0a3e6fffb37e05119bd2c8cd;p=dbsrgits%2FDBIx-Class-Historic.git diff --git a/lib/DBIx/Class/CDBICompat/HasA.pm b/lib/DBIx/Class/CDBICompat/HasA.pm index fe85214..647674f 100644 --- a/lib/DBIx/Class/CDBICompat/HasA.pm +++ b/lib/DBIx/Class/CDBICompat/HasA.pm @@ -1,28 +1,46 @@ -package DBIx::Class::CDBICompat::HasA; +package # hide from PAUSE + DBIx::Class::CDBICompat::HasA; use strict; use warnings; sub has_a { - my ($self, $col, $f_class) = @_; - $self->throw( "No such column ${col}" ) unless $self->_columns->{$col}; - eval "require $f_class"; - my ($pri, $too_many) = keys %{ $f_class->_primaries }; - $self->throw( "has_a only works with a single primary key; ${f_class} has more" ) - if $too_many; - $self->add_relationship($col, $f_class, - { "foreign.${pri}" => "self.${col}" }, - { _type => 'has_a' } ); - $self->inflate_column($col, - { inflate => sub { - my ($val, $self) = @_; - return ($self->search_related($col, {}, {}))[0] - || $f_class->new({ $pri => $val }); }, - deflate => sub { - my ($val, $self) = @_; - $self->throw("$val isn't a $f_class") unless $val->isa($f_class); - return ($val->_ident_values)[0] } } ); + my ($self, $col, $f_class, %args) = @_; + $self->throw_exception( "No such column ${col}" ) unless $self->has_column($col); + $self->ensure_class_loaded($f_class); + if ($args{'inflate'} || $args{'deflate'}) { # Non-database has_a + if (!ref $args{'inflate'}) { + my $meth = $args{'inflate'}; + $args{'inflate'} = sub { $f_class->$meth(shift); }; + } + if (!ref $args{'deflate'}) { + my $meth = $args{'deflate'}; + $args{'deflate'} = sub { shift->$meth; }; + } + $self->inflate_column($col, \%args); + return 1; + } + + $self->belongs_to($col, $f_class); return 1; } +sub search { + my $self = shift; + my $attrs = {}; + if (@_ > 1 && ref $_[$#_] eq 'HASH') { + $attrs = { %{ pop(@_) } }; + } + my $where = (@_ ? ((@_ == 1) ? ((ref $_[0] eq "HASH") ? { %{+shift} } : shift) + : {@_}) + : undef()); + if (ref $where eq 'HASH') { + foreach my $key (keys %$where) { # has_a deflation hack + $where->{$key} = ''.$where->{$key} + if eval { $where->{$key}->isa('DBIx::Class') }; + } + } + $self->next::method($where, $attrs); +} + 1;