Wednesday, March 21, 2012

Overriding insert in DBIx::Class

Sometimes when working with DBIX::Class whenever you create a record
in a table, you want to create another record in a corresponding
table. Are you going to go and sift through your code base looking for
all code that writes to the table? Not when you can change your schema
class to handle the action for you.

In order to do this we can override the insert method. This example is
taken from DBIx::Class::Manual::Cookbook :

sub insert {
  my ( $self, @args ) = @_;
  $self->create_related ('cds', \%initial_cd_data );
  return $self;

You see above that next::method is called and then a record is
inserted in a related field. Be aware that you need to call
next::method before you call create so that you write the original
call before making the new one.

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;

 or after:

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

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