Don’t Repeat Yourself: JSON
Author: fREW Schmidt
18
May
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| 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:
1 2 3 4 5 6 7 8
| 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.
2 Responses for "Don’t Repeat Yourself: JSON"
Why not use $self->result_source->columns? Even shorter =)
@Yuval: that’s true until you do it more than once.
Leave a reply