From: Dave Rolsky Date: Mon, 23 Jun 2008 03:11:04 +0000 (+0000) Subject: Make the immutable constructor provide the same nice error message for X-Git-Tag: 0_55~101 X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=93e9857863376eaf0a6bd18d0cbd1bac138a6b91;p=gitmo%2FMoose.git Make the immutable constructor provide the same nice error message for a single non-hashref arg as Moose::Object does. --- diff --git a/Changes b/Changes index 8c787a6..570637a 100644 --- a/Changes +++ b/Changes @@ -12,6 +12,12 @@ Revision history for Perl extension Moose provide its own implementation. See Recipe 11 for an example of all this. (thanks Dave Rolsky) - added tests for this + * Moose::Meta::Method::Constructor + - when a single argument that wasn't a hashref was provided to + an immutabilized constructor, the error message was very + unhelpful, as opposed to the non-immutable error. Reported by + dew. (Thanks to Dave Rolsky) + - added test for this (also Dave Rolsky) 0.50 Thurs. Jun 11, 2008 - Fixed a version number issue by bumping all modules diff --git a/lib/Moose/Meta/Method/Constructor.pm b/lib/Moose/Meta/Method/Constructor.pm index b633704..54921cd 100644 --- a/lib/Moose/Meta/Method/Constructor.pm +++ b/lib/Moose/Meta/Method/Constructor.pm @@ -75,6 +75,9 @@ sub initialize_body { $source .= "\n" . 'return $class->Moose::Object::new(@_)'; $source .= "\n" . ' if $class ne \'' . $self->associated_metaclass->name . '\';'; + $source .= "\n" . 'confess "Single parameters to new() must be a HASH ref"'; + $source .= "\n" . ' if scalar @_ == 1 && defined $_[0] && ref($_[0]) ne q{HASH};'; + $source .= "\n" . 'my %params = (scalar @_ == 1) ? %{$_[0]} : @_;'; $source .= "\n" . 'my $instance = ' . $self->meta_instance->inline_create_instance('$class'); diff --git a/t/300_immutable/008_immutable_constructor_error.t b/t/300_immutable/008_immutable_constructor_error.t new file mode 100644 index 0000000..1c235f4 --- /dev/null +++ b/t/300_immutable/008_immutable_constructor_error.t @@ -0,0 +1,35 @@ +#!/usr/bin/perl + +use strict; +use warnings; + +use Test::More tests => 3; +use Test::Exception; + +BEGIN { + use_ok('Moose'); +} + +=pod + +This tests to make sure that we provide the same error messages from +an immutable constructor as is provided by a non-immutable +constructor. + +=cut + +{ + package Foo; + use Moose; + + has 'foo' => (is => 'rw', isa => 'Int'); + + Foo->meta->make_immutable(debug => 0); +} + +my $scalar = 1; +throws_ok { Foo->new($scalar) } qr/\QSingle parameters to new() must be a HASH ref/, + 'Non-ref provided to immutable constructor gives useful error message'; +throws_ok { Foo->new(\$scalar) } qr/\QSingle parameters to new() must be a HASH ref/, + 'Scalar ref provided to immutable constructor gives useful error message'; +