aboutsummaryrefslogtreecommitdiffstats
path: root/lib/Reaction/UI/ViewPort/Field/Role/Choices.pm
blob: b3525cbf9beb4487f11f285bd61eaeb3163afd66 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package Reaction::UI::ViewPort::Field::Role::Choices;

use Reaction::Role;
use URI;
use Scalar::Util 'blessed';

use namespace::clean -except => [ qw(meta) ];
use MooseX::Types::Moose qw/ArrayRef Str/;

has valid_values  => (isa => ArrayRef, is => 'ro', lazy_build => 1);
has value_choices => (isa => ArrayRef, is => 'ro', lazy_build => 1);
has value_map_method => (
  isa => Str, is => 'ro', required => 1, default => sub { 'display_name' },
);
sub str_to_ident {
  my ($self, $str) = @_;
  my $u = URI->new('','http');
  $u->query($str);
  return ($u->query_keywords ? ($u->query_keywords)[0] : { $u->query_form });
};
sub obj_to_str {
  my ($self, $obj) = @_;
  return $obj unless ref($obj);
  confess "${obj} not an object" unless blessed($obj);
  my $ident = $obj->ident_condition; #XXX DBIC ism that needs to go away
  my $u = URI->new('', 'http');
  $u->query_form(%$ident);
  return $u->query;
};
sub obj_to_name {
  my ($self, $obj) = @_;
  return $obj unless ref($obj);
  confess "${obj} not an object" unless blessed($obj);
  my $meth = $self->value_map_method;
  return $obj->$meth;
};
sub _build_valid_values {
  my $self = shift;
  return [ $self->attribute->all_valid_values($self->model) ];
};
sub _build_value_choices {
  my $self  = shift;
  my @pairs = map{{value => $self->obj_to_str($_), name => $self->obj_to_name($_)}}
    @{ $self->valid_values };
  return [ sort { $a->{name} cmp $b->{name} } @pairs ];
};



1;