Skip to content

Commit

Permalink
now handles initialized values too
Browse files Browse the repository at this point in the history
  • Loading branch information
jberger committed Mar 31, 2012
1 parent e8a64b5 commit ce6c8ef
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 3 deletions.
1 change: 1 addition & 0 deletions README
@@ -0,0 +1 @@
A Moose Trait for remembering the history of a variable. On each write, the new value is also stored in an extra array
18 changes: 15 additions & 3 deletions lib/MooseX/RememberHistory/Trait/Attribute.pm
Expand Up @@ -24,7 +24,7 @@ around 'install_accessors' => sub {


my $class = $attr->associated_class; my $class = $attr->associated_class;
my $hist_name = $attr->history_getter; my $hist_name = $attr->history_getter;

#add history holder #add history holder
$class->add_attribute( $class->add_attribute(
$hist_name => ( $hist_name => (
Expand All @@ -36,9 +36,21 @@ around 'install_accessors' => sub {


$attr->$orig(@_); $attr->$orig(@_);


my $writer_name = $attr->get_write_method; # sync history on first access
$class->add_around_method_modifier($hist_name, sub{
my $orig = shift;
my $self = shift;
my $history = $self->$orig(@_);
unless (@$history) {
my $old_val = $attr->get_value($self);
push @$history, $old_val if defined $old_val;
}
return $history;
});


$class->add_after_method_modifier($writer_name, sub{ # push on to history on write
my $writer_name = $attr->get_write_method;
$class->add_before_method_modifier($writer_name, sub{
my ($self, $value) = @_; my ($self, $value) = @_;
return unless defined $value; return unless defined $value;
my $history = $self->can($hist_name)->($self); my $history = $self->can($hist_name)->($self);
Expand Down
7 changes: 7 additions & 0 deletions t/basic.t
Expand Up @@ -29,6 +29,13 @@ use Test::More;
is_deeply($obj->x_history, [ 1 ], 'history appended'); is_deeply($obj->x_history, [ 1 ], 'history appended');
} }


{
my $obj = My::Class->new( x => 2 );
is( $obj->x, 2, "Initial value exists" );
$obj->x(3);
is_deeply( $obj->x_history, [ 2, 3 ], "Initial value also exists in history" );
}

{ {
package My::Class::Position; package My::Class::Position;
use Moose; use Moose;
Expand Down

0 comments on commit ce6c8ef

Please sign in to comment.