Search code examples
perlrecursionmoose

How to prevent infinite recursion (with Moose)?


In the following code fragment (Perl with Moose) there seems to be an infinite recursion:

has 'ORM' => ( is     => 'ro',
               isa     => 'Model::LazySQLModel',
               lazy    => 1,
               builder => 'ORM_builder' );

has 'id' => ( is        => 'ro',
              isa       => 'Int',
              lazy      => 1,
              builder   => 'id_builder',
              predicate => 'has_id',
            );

sub id_builder { $_[0]->ORM->id }

sub ORM_builder {
  my ($self) = @_;

  # FIXME: looks like infinite recursion
  if ($self->id) {
    return $self->ORM_find();
  } else {
    return $self->ORM_insert();
  }
}

Remark: Model::LazySQLModel is a tied hash which holds ID and other DB fields.

What is the right way to do this (to be sure that we prevent infinite recursion)?


Solution

  • Replacing if ($self->id) with if ($self->has_id) is a solution.