Showing posts with label Moose. Show all posts
Showing posts with label Moose. Show all posts

Tuesday, March 6, 2012

before, after, and around Moose


One of the things I like about Moose is its method modifiers. They
provide an easy interface to modifying methods without disturbing
them. What's more is that they are stupidly simple.

the three modifiers are "before", "after", and "around". "before" and
"after" are simple in that they allow you to run code before or after
a given method So whether you want to ensure something happens
before you run a method:

  before 'wear_boots' => sub {
      my $self = shift;
      $self->wear_socks;
  };

 or after:

  after 'use_bathroom' => sub {
      my $self = shift;
      $self->wash_hands;
  };

You can be sure that you can make it happen without disturbing the way
that the method is supposed to run.

The "around" modifier provides a lot more flexibility. It receives the
original method, the object, and then any arguments that are passed to
it. This way you can execute the original method depending on your own logic:

  around 'eat' => sub {
      my $orig = shift;
      my $self = shift;

      if ($self->time_of day eq "morning") {
         $self->{meal_type} = "breakfast";
      }
      elsif ($self->time_of day eq "afternoon") {
         $self->{meal_type} = "lunch";
      }
      elseif ($self->time_of day eq "evening") {
         $self->{meal_type} = "dinner";
      }
      return $self->$orig(@)
  };

Moose is great because it provides a simple syntax that abbreviates OO
Perl's boilerplate requirements. These modifiers are a perfect example
of this. They make overriding methods easy. The relevant documentation in the cpan is here