DBIx-Class-Helper-Row-Enumeration

 view release on metacpan or  search on metacpan

lib/DBIx/Class/Helper/Row/Enumeration.pm  view on Meta::CPAN

package DBIx::Class::Helper::Row::Enumeration;

# ABSTRACT: Add methods for emum values

use v5.10.1;

use strict;
use warnings;

use Ref::Util  ();
use Sub::Quote ();

# RECOMMEND PREREQ: Ref::Util::XS

our $VERSION = 'v0.1.8';

# The names of all methods installed by this module.
my %MINE;



sub add_columns {
    my ( $self, @cols ) = @_;

    $self->next::method(@cols);

    my $class = Ref::Util::is_ref($self) || $self;

    foreach my $col (@cols) {

        next if ref $col;

        $col =~ s/^\+//;
        my $info = $self->column_info($col);

        next unless $info->{data_type} eq 'enum';

        next unless exists $info->{extra}{list};

        my $handlers = $info->{extra}{handles} //= sub { "is_" . $_[0] };

        next unless $handlers;

        if ( Ref::Util::is_plain_coderef($handlers) ) {
            $info->{extra}{handles} = {
                map {

                    if ( my $method = $handlers->( $_, $col, $class ) ) {
                        ( $method => $_ )
                    }
                    else {
                        ()
                    }

                } @{ $info->{extra}{list} }
            };
            $handlers = $info->{extra}{handles};
        }

        DBIx::Class::Exception->throw("handles is not a hashref")
          unless Ref::Util::is_plain_hashref($handlers);

        foreach my $handler ( keys %$handlers ) {
            next unless $handler;
            my $value = $handlers->{$handler} or next;

            my $method = "${class}::${handler}";

            # Keep track of what we've installed, and don't complain about
            # being asked to reinstall it. This is needed when using
            # DBIx::Class::Schema::Loader. In theory we should check whether
            # the current method is the one we installed, and throw anyway if
            # it isn't, but this seems adequate.
            DBIx::Class::Exception->throw("${method} is already defined")
              if $self->can($method) && !$MINE{$method};

            my $code =
              $info->{is_nullable}
              ? qq{ my \$val = \$_[0]->get_column("${col}"); }
              . qq{ defined(\$val) && \$val eq "${value}" }
              : qq{ \$_[0]->get_column("${col}") eq "${value}" };

            $MINE{$method} = 1;
            Sub::Quote::quote_sub $method, $code;

        }

    }

    return $self;
}


1;

__END__

=pod

=encoding UTF-8

=head1 NAME

DBIx::Class::Helper::Row::Enumeration - Add methods for emum values

=head1 VERSION

version v0.1.8

=head1 SYNOPSIS

In your result class:

  use base qw/DBIx::Class::Core/;

  __PACKAGE__->load_components(qw/ Helper::Row::Enumeration /);

  __PACKAGE__->add_column(

    foo => {
        data_type => 'enum',



( run in 0.760 second using v1.01-cache-2.11-cpan-39bf76dae61 )