develooper Front page | perl.moose | Postings from June 2011

RE: Moose Type Constraints violations to warnings?

Thread Previous | Thread Next
From:
Edward Allen
Date:
June 10, 2011 12:58
Subject:
RE: Moose Type Constraints violations to warnings?
Message ID:
BLU151-w5636BCF5033F46B8C32183BE640@phx.gbl
package MyApp::Room;
use Mouse;
use Mouse::Util::TypeConstraints;
use Carp qw(cluck);
use Scalar::Util qw(looks_like_number);

use feature 'switch';

# Subtype and coercion
subtype 'Price'
    => as 'Num';


coerce 'Price'
    => from 'Str'
    => via { 
        given($_) {                 
            # Anything like a number is OK
            when (looks_like_number $_) {     
                return $_;
            }
            # $9.99  is ok.
            when(/ \A \$(\d+\.?\d+?) \z /xms) {
                return $1;
            }
            # $.99 is ok
            when(/ \A \$(\d+?\.\d+) \z /xms) {
                return $1;
            }
            # Complain about anything else.
            default {
                cluck 'Price must be a number!  Setting to $0.00';
                return 0;
            }
         }
     };

has 'price_in' => (
    is => 'rw',
    perdicate => 'has_price_in',
    trigger => sub {
        my ($self,$val) = @_;
        $self->price($val);
    }
);

has 'price' => (
    is => 'rw',
    isa => 'Price',
    coerce => 1,
);


package main;

use feature 'say';

my $room = MyApp::Room->new( price_in => '3.50' );

say "Room price: " . $room->price();

$room->price_in('1000');

say "Room price: " . $room->price();

$room->price_in('cheap');

say "Room price: " . $room->price();



Thread Previous | 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