develooper Front page | perl.moose | Postings from September 2014

Coerce and messages

Thread Next
From:
Bill Moseley
Date:
September 28, 2014 20:28
Subject:
Coerce and messages
Message ID:
CAKhN_m61GyWHmChm7aMsmR2yyyZmU9SOf=r7g5VcK3yXW96yXw@mail.gmail.com
I'm going to build a request with HTTP::Request::Common and want to use its
existing methods (POST, PUT, GET, etc.)

I'm curious how to control the error message better when coercing.


My class gets an HTTP method name as an attribute, and I wanted to validate
it for how it will get used:

subtype HttpMethod =>
    as 'Str',
    where { HTTP::Request::Common->can( $_ ) },
    message { "The method provided [$_] does not appear to be a valid HTTP
method" };


has http_method => (
    is => 'ro',
    isa => 'HTTPMethod',
    required => 1,
);


So, that generates a nice error message.


This is ugly, but to build the request I was then doing:

my $sub = HTTP::Request::Common->can( $self->http_method );
my $http_request = $sub->( $url, @args );


I thought I'd coerce the method name to that code reference and I would
then use just:

my $http_request = $self->http_method->( $url, @args );



Not sure I have this correct, but the code to coerce is now:


subtype HttpRequestCode => as 'CodeRef';

subtype HttpMethod =>
    as 'Str',
    where { HTTP::Request::Common->can( $_ ) },
    message { "The method provided [$_] does not appear to be a valid HTTP
method" };

coerce HttpRequestCode =>
    from 'HttpMethod' => via { HTTP::Request::Common->can( $_ ) };

has http_method => (
    is => 'ro',
    isa => 'HttpRequestCode',
    coerce => 1,
    required => 1,
);


I get an OK message:

Attribute (http_method) does not pass the type constraint because:
Validation failed for 'HttpRequestCode' with value "PSOT"


but is there a way I can use my "message" while still coercing?



-- 
Bill Moseley
moseley@hank.org

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About