Don't Repeat Yourself: JSON

With DBIx::Class we typically have a TO_JSON method which returns a hashref of the data you want in your json. Here’s an example:

sub TO_JSON {
   my $self = shift;
   return {
      id => $self->id,
      name => $self->name,
      comments => $self->comments,
      email => $self->email,
      job => $self->job,
      ok => $self->ok,
      i_cant => $self->i_cant,
      think_of => $self->think_ok,
      anymore => $self->anymore,
   };
}

Here’s the shorter version mst inspired me to write:

sub TO_JSON {
   my $self = shift;
   return {
      map { $_ => self->$_ }
         qw{ id name comments email job
            ok i_cant think_of anymore },
   };
}

Anyway, not very complex, but still awesome.

Posted Tue, May 19, 2009

If you're interested in being notified when new posts are published, you can subscribe here; you'll get an email once a week at the most.