use warnings;
use Scalar::Util 'blessed';
+use Carp 'confess';
use MRO::Compat;
sub linearized_isa { @{ mro::get_linear_isa($_[0]->name) } }
+sub clone_object {
+ my $class = shift;
+ my $instance = shift;
+
+ (blessed($instance) && $instance->isa($class->name))
+ || confess "You must pass an instance ($instance) of the metaclass (" . $class->name . ")";
+
+ $class->clone_instance($instance, @_);
+}
+
+sub clone_instance {
+ my ($class, $instance, %params) = @_;
+
+ (blessed($instance))
+ || confess "You can only clone instances, \$self is not a blessed instance";
+
+ my $clone = bless { %$instance }, ref $instance;
+
+ foreach my $attr ($class->compute_all_applicable_attributes()) {
+ if ( defined( my $init_arg = $attr->init_arg ) ) {
+ if (exists $params{$init_arg}) {
+ $clone->{ $attr->name } = $params{$init_arg};
+ }
+ }
+ }
+
+ return $clone;
+
+}
+
+
1;
__END__
--- /dev/null
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+
+use Test::More 'no_plan';
+
+{
+ package Foo;
+ use Mouse;
+
+ has foo => (
+ isa => "Str",
+ is => "rw",
+ default => "foo",
+ );
+
+ has bar => (
+ isa => "ArrayRef",
+ is => "rw",
+ );
+
+ sub clone {
+ my ( $self, @args ) = @_;
+ $self->meta->clone_object( $self, @args );
+ }
+}
+
+my $foo = Foo->new( bar => [ 1, 2, 3 ] );
+
+is( $foo->foo, "foo", "attr 1", );
+is_deeply( $foo->bar, [ 1 .. 3 ], "attr 2" );
+
+my $clone = $foo->clone( foo => "dancing" );
+
+is( $clone->foo, "dancing", "overridden attr" );
+is_deeply( $clone->bar, [ 1 .. 3 ], "clone attr" );
+