| 1 | package Catalyst::View::Valiant::JSONBuilder; | ||
| 2 | |||
| 3 | use Moo; | ||
| 4 | use Carp; | ||
| 5 | use Module::Runtime 'use_module'; | ||
| 6 | |||
| 7 | extends 'Catalyst::View::BasePerRequest'; | ||
| 8 | |||
| 9 | our $MODEL_BUILDER = 'Valiant::JSON::JSONBuilder'; | ||
| 10 | |||
| 11 | has 'model_builder' => ( | ||
| 12 | is=>'ro', | ||
| 13 | required=>1, | ||
| 14 | default=>sub { $MODEL_BUILDER }, | ||
| 15 | ); | ||
| 16 | |||
| 17 | sub get_model_for_json { | ||
| 18 | my ($self, $name) = @_; | ||
| 19 | return $self->to_model if $self->can('to_model'); | ||
| 20 | return $self->get_attribute_for_json($name) if $self->can('get_attribute_for_json'); | ||
| 21 | return $self->$name if $self->can($name); | ||
| 22 | croak "Can't find model for $name"; | ||
| 23 | } | ||
| 24 | |||
| 25 | sub json_builder { | ||
| 26 | my ($self, $model) = @_; | ||
| 27 | return my $jb = use_module($self->model_builder)->new(view => $self, model=>$model); | ||
| 28 | } | ||
| 29 | |||
| 30 | sub render { | ||
| 31 | my ($self, $c, @args) = @_; | ||
| 32 | my $jb = $self->render_json($c, @args); | ||
| 33 | return $jb->render_json; | ||
| 34 | } | ||
| 35 | |||
| 36 | __PACKAGE__->config(content_type=>'application/json'); | ||
| 37 | |||
| 38 | =head1 NAME | ||
| 39 | |||
| 40 | Catalyst::View::Valiant::JSONBuilder - Per Request, JSON view that wraps a model | ||
| 41 | |||
| 42 | =head1 SYNOPSIS | ||
| 43 | |||
| 44 | =head1 DESCRIPTION | ||
| 45 | |||
| 46 | =head1 ATTRIBUTES | ||
| 47 | |||
| 48 | This class inherits all of the attributes from L<Catalyst::View::BasePerRequest> | ||
| 49 | |||
| 50 | =head1 METHODS | ||
| 51 | |||
| 52 | This class inherits all of the methods from L<Catalyst::View::BasePerRequest> as well as: | ||
| 53 | |||
| 54 | =head1 EXPORTS | ||
| 55 | |||
| 56 | =head1 SUBCLASSING | ||
| 57 | |||
| 58 | You can subclass this view in order to provide your own default behavior and additional methods. | ||
| 59 | |||
| 60 | =head1 SEE ALSO | ||
| 61 | |||
| 62 | L<Catalyst::View>, L<JSON::MaybeXS>, L<Catalyst::View::BasePerRequest> | ||
| 63 | |||
| 64 | =head1 AUTHOR | ||
| 65 | |||
| 66 | See L<Valiant> | ||
| 67 | |||
| 68 | =head1 COPYRIGHT & LICENSE | ||
| 69 | |||
| 70 | See L<Valiant> | ||
| 71 | |||
| 72 | =cut |