Permalink
Browse files

now handles initialized values too

  • Loading branch information...
1 parent e8a64b5 commit ce6c8efa4cc7cd22fa3dce4fd8361b28b093d660 @jberger committed Mar 31, 2012
Showing with 23 additions and 3 deletions.
  1. +1 −0 README
  2. +15 −3 lib/MooseX/RememberHistory/Trait/Attribute.pm
  3. +7 −0 t/basic.t
View
1 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
View
18 lib/MooseX/RememberHistory/Trait/Attribute.pm
@@ -24,7 +24,7 @@ around 'install_accessors' => sub {
my $class = $attr->associated_class;
my $hist_name = $attr->history_getter;
-
+
#add history holder
$class->add_attribute(
$hist_name => (
@@ -36,9 +36,21 @@ around 'install_accessors' => sub {
$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) = @_;
return unless defined $value;
my $history = $self->can($hist_name)->($self);
View
7 t/basic.t
@@ -30,6 +30,13 @@ use Test::More;
}
{
+ 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;
use Moose;
extends 'My::Class';

0 comments on commit ce6c8ef

Please sign in to comment.