File: hash.t

package info (click to toggle)
libhtml-formhandler-perl 0.40057-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 2,320 kB
  • ctags: 685
  • sloc: perl: 8,849; makefile: 2
file content (74 lines) | stat: -rw-r--r-- 1,636 bytes parent folder | download | duplicates (5)
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74

use strict;
use warnings;
use Test::More;

{
  package MyApp::Form::RepHash;
  use HTML::FormHandler::Moose;
  extends 'HTML::FormHandler';

  has_field 'lookup' => (
    type => 'Repeatable',
    inflate_default_method => \&inflate_default,
    deflate_value_method => \&deflate_value,
  );
  has_field 'lookup.key';
  has_field 'lookup.value';

  sub inflate_default {
    my ($self, $value) = @_;
    # convert hash to array of hashes
    # { k1 => v1, k2 => v2 } becomes
    #   [ { key => k1, value => v1 }, { key => k2, value => v2 } ]
    return [map +{key => $_, value => $value->{$_}}, sort keys %$value];
  }

  sub deflate_value {
    my ($self, $value) = @_;
    # convert array of hashes to hash
    # [ { key => k1, value => v1 }, { key => k2, value => v2 } ] becomes
    #   { k1 => v1, k2 => v2 }
    return { map { ($_->{'key'} => $_->{'value'}) } @$value };
  }

  no HTML::FormHandler::Moose;
  1;
}

my $form = MyApp::Form::RepHash->new;
ok( $form );
my $item = {
  'lookup' => {
    'k1' => 'v1',
    'k2' => 'v2',
  }
};
my $params = {
  'lookup.0.key'   => 'k1',
  'lookup.0.value' => 'v1',
  'lookup.1.key'   => 'k2',
  'lookup.1.value' => 'v2',
};
my $inflated = {
  'lookup' => [
    { key => 'k1', value => 'v1' },
    { key => 'k2', value => 'v2' },
  ],
};

{
  $form->process(item => $item);
  my $fif = $form->fif;
  my $value = $form->value;
  is_deeply( $fif, $params, 'fif is correct' );
  is_deeply( $value, $inflated, 'value from item is correct' );
}

{
  $form->process(params => $params);
  my $value = $form->value;
  is_deeply( $value, $item, 'value from params is correct' );
}

done_testing;