Stories
Slash Boxes
Comments
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More | Login | Reply
Loading... please wait.
  • So, in the interest of TIMTOWTDI, here is another approach that uses coercion to extract the params list from the controller object.

    package PIPs::QueryParams;
    use Moose;
    use Moose::Util::TypeContraints;
    use PIPs::QueryParams::Param;

    # I am assuming this is the name
    # of your controller class and
    # it is a non-Moose class, if it is
    # a Moose class, you can remove this
    # (assuming the class is already loaded)
    # because Moose does this for you
    class_type 'PIPs::Controller';

    subtype 'PIPs::ListOfParams'
        => as 'ArrayRef[PIPs::QueryParams::Param]';

    coerce 'PIPs::ListOfParams'
        => from 'PIPs::Controller'
        => via {
            my $controller = $_;
            my @params;
            my $allowed_query_params = $controller->allowed_query_params;
            foreach my $name ( sort keys  %$allowed_query_params) {
                my $args = $allowed_query_params->{$name};
                $args->{name} = $name;
                push @params => PIPs::QueryParams::Param->new(%$args);
            }
            return \@params;
        };

    has params => (
        is     => 'ro',
        isa    => 'PIPs::ListOfParams',
        coerce => 1,
    );

    __PACKAGE__->meta->make_immutable;

    no Moose; 1;

    And then your code would look like this ...

    my $params = PIPs::QueryParams->new( params => $controller );
    my $list   = $params->params;
    say $_->name foreach @$list;

    Now, passing a controller where your supposed to pass params does seem a little odd, so perhaps this isnt the best example. However you could just as easily pass in the $controller->allowed_query_params and do the coercion on the HashRef[HashRef] type (or better yet, use MooseX::Types::Structured to define a stricter Dictionary type).

    One of the benefits I see with using types and coercion is that since types are global, this promotes cross cutting re-use since now any class that needs a list of PIPs::QueryParams::Param objects and happens to have easy access to a $controller object can use this coercion.

    Anyway, glad your enjoying the Moose :)

    - Stevan