On Mon, Sep 12, 2011 at 8:01 AM, Roland Philibert rphilib...@aptina.com
wrote:
I am trying to fetch data from a mysql database using a jQuery ajax method
to populate a select list...and my question is: what is the recommended
method in Catalyst to serialize/encode a DBIC class object into a JSON
object, that I can then parse easily in a view with javascript?
I can't tell you what's recommended (I'm pretty new to Catalyst myself), but
I'm pretty happy with my generic solution.
# extend Catalyst::View::JSON.
# I got this idea from something on the CPAN.
package MyApp::View::JSON;
use Moose;
use JSON::XS ();
extends 'Catalyst::View::JSON';
# TODO: become smarter Mooser and delegate or something...
my $encoder = JSON::XS-new-utf8-pretty(0)-indent(0)
-allow_blessed(1)-convert_blessed(1);
sub encode_json {
my( $self, $c, $data ) = @_;
$encoder-encode( $data );
}
# create a result base class with a generic TO_JSON method:
package MyApp::Schema::DB::ResultBase;
use Moose;
use MooseX::NonMoose;
use namespace::autoclean;
extends 'DBIx::Class::Core';
sub TO_JSON {
return { $_[0]-get_inflated_columns };
}
1;
# result classes extend the base class
package MyApp::Schema::DB::Result::Example;
...
extends 'MyApp::Schema::DB::ResultBase';
...
# in controller methods to return JSON...
...
$c-stash(
current_view = 'JSON',
current_model = 'DB',
);
...
$c-stash(
json_data = [ $c-model()-... ],
);
___
List: Catalyst@lists.scsys.co.uk
Listinfo: http://lists.scsys.co.uk/cgi-bin/mailman/listinfo/catalyst
Searchable archive: http://www.mail-archive.com/catalyst@lists.scsys.co.uk/
Dev site: http://dev.catalyst.perl.org/