Skip to content

Instantly share code, notes, and snippets.

@chy-causer

chy-causer/diff Secret

Created April 28, 2017 16:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chy-causer/21a6d749afe7e74a3436082df15e5aad to your computer and use it in GitHub Desktop.
Save chy-causer/21a6d749afe7e74a3436082df15e5aad to your computer and use it in GitHub Desktop.
Add once and as_array "filters" to Mojolicious
diff --git a/lib/Mojolicious/Validator/Validation.pm b/lib/Mojolicious/Validator/Validation.pm
index b46d63552..d702daa62 100644
--- a/lib/Mojolicious/Validator/Validation.pm
+++ b/lib/Mojolicious/Validator/Validation.pm
@@ -68,11 +68,16 @@ sub optional {
return $self->topic($name) unless defined(my $input = $self->input->{$name});
+ my %filters = map { ($_ => 1) } @filters;
+ my ($wantarray, $wantscalar)
+ = (delete $filters{as_array}, delete $filters{once});
+
my @input = ref $input eq 'ARRAY' ? @$input : ($input);
- for my $cb (map { $self->validator->filters->{$_} } @filters) {
+ for my $cb (map { $self->validator->filters->{$_} } keys %filters) {
@input = map { $self->$cb($name, $_) } @input;
}
- $self->output->{$name} = ref $input eq 'ARRAY' ? \@input : $input[0]
+ $self->output->{$name}
+ = ref $input eq 'ARRAY' && !$wantscalar || $wantarray ? \@input : $input[-1]
if @input && !grep { !length } @input;
return $self->topic($name);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment