Commit | Line | Data |
ddccc6a2 |
1 | package Reaction::UI::ViewPort::Field::Role::Choices; |
2 | |
c8fbb8ad |
3 | use Reaction::Role; |
ddccc6a2 |
4 | use URI; |
5 | use Scalar::Util 'blessed'; |
6 | |
7 | role Choices, which { |
8 | |
9 | has valid_values => (isa => 'ArrayRef', is => 'ro', lazy_build => 1); |
10 | has value_choices => (isa => 'ArrayRef', is => 'ro', lazy_build => 1); |
11 | has value_map_method => ( |
12 | isa => 'Str', is => 'ro', required => 1, default => sub { 'display_name' }, |
13 | ); |
14 | |
15 | implements str_to_ident => as { |
16 | my ($self, $str) = @_; |
17 | my $u = URI->new('','http'); |
18 | $u->query($str); |
19 | return { $u->query_form }; |
20 | }; |
21 | |
22 | implements obj_to_str => as { |
23 | my ($self, $obj) = @_; |
24 | return $obj unless ref($obj); |
25 | confess "${obj} not an object" unless blessed($obj); |
26 | my $ident = $obj->ident_condition; #XXX DBIC ism that needs to go away |
27 | my $u = URI->new('', 'http'); |
28 | $u->query_form(%$ident); |
29 | return $u->query; |
30 | }; |
31 | |
32 | implements obj_to_name => as { |
33 | my ($self, $obj) = @_; |
34 | return $obj unless ref($obj); |
35 | confess "${obj} not an object" unless blessed($obj); |
36 | my $meth = $self->value_map_method; |
37 | return $obj->$meth; |
38 | }; |
39 | |
40 | implements _build_valid_values => as { |
41 | my $self = shift; |
42 | return [ $self->attribute->all_valid_values($self->action) ]; |
43 | }; |
44 | |
45 | implements _build_value_choices => sub{ |
46 | my $self = shift; |
47 | my @pairs = map{{value => $self->obj_to_str($_), name => $self->obj_to_name($_)}} |
48 | @{ $self->valid_values }; |
49 | return [ sort { $a->{name} cmp $b->{name} } @pairs ]; |
50 | }; |
51 | |
52 | }; |
53 | |
54 | 1; |