Created
March 11, 2011 00:39
-
-
Save mstratman/865264 to your computer and use it in GitHub Desktop.
Subclassing non-Moose classes example 2.2 - From http://blogs.perl.org/users/mark_a_stratman/2011/03/subclassing-tricky-non-moose-classes-constructor-problems.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# NOTE: This is simply an example of a legacy blessed-hash object. | |
# I do not recommend using it. | |
package Animal2; | |
use strict; | |
sub new { | |
my $class = shift; | |
my $self = {}; | |
$self->{_name} = shift; | |
bless($self, $class); | |
return $self; | |
} | |
sub name { | |
my $self = shift; | |
if (@_) { $self->{_name} = shift } | |
return $self->{_name}; | |
} | |
1; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package Camel; | |
use Moose; | |
use MooseX::NonMoose; | |
extends 'Animal2'; | |
has 'humps' => ( is => 'ro', isa => 'Num' ); | |
# Make sure Moose::Object parent gets a hashref with 'humps' in it | |
around BUILDARGS => sub { | |
my $orig = shift; | |
my $class = shift; | |
# We expect this to be called with: Camel->new($name, $optional_humps) | |
# so @_ contains a name, and possibly a number of humps. | |
my $camel_name = shift; | |
my $camel_humps = shift; | |
my $moose_args = {}; | |
$moose_args->{humps} = $camel_humps if defined $camel_humps; | |
# Give Moose constructor what it wants | |
return $class->$orig($moose_args); | |
}; | |
# Make sure Animal2 parent only gets a name | |
sub FOREIGNBUILDARGS { | |
my $class = shift; | |
my $name = shift; | |
my $humps = shift; # We are going to ignore this. | |
# Whatever we return will be sent to Animal2->new() | |
return $name; | |
} | |
no Moose; | |
__PACKAGE__->meta->make_immutable; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
use Modern::Perl; | |
use Camel; | |
my $c = Camel->new("Samuel Camel", 2); | |
say $c->name, " has ", $c->humps, " humps"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment