# HG changeset patch # User wizard # Date 1275884486 -14400 # Node ID 79cdd6c86409806bd1de092d9f0fb2b048775720 # Parent 0475eb382085642bb4e10252f25232ddbd948a6e JSON support (experimental) diff -r 0475eb382085 -r 79cdd6c86409 Lib/IMPL/Web/QueryHandler/JsonFormat.pm --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Lib/IMPL/Web/QueryHandler/JsonFormat.pm Mon Jun 07 08:21:26 2010 +0400 @@ -0,0 +1,80 @@ +package IMPL::Web::QueryHandler::JsonTransform; +package IMPL::Web::QueryHandler::JsonFormat; +use strict; +use base qw(IMPL::Web::QueryHandler); + +__PACKAGE__->PassThroughArgs; + +use Error qw(:try); +use JSON; + +sub Process { + my ($this,$action,$nextHandler) = @_; + + my $transform = new IMPL::Web::QueryHandler::JsonTransform(); + + my $result; + try { + $result = $nextHandler->(); + } otherwise { + my $err = shift; + $result = { error => $err }; + }; + + $action->response->contentType('text/javascript'); + my $hout = $action->response->streamBody; + print $hout to_json($result, {pretty => 1} ); +} + +package IMPL::Web::QueryHandler::JsonTransform; + +use base qw(IMPL::Transform); +use IMPL::Class::Property; + +BEGIN { + public property cacheClassProps => prop_all; +} + +our %CTOR = ( + 'IMPL::Transform' => sub { + + -plain => sub { $_[1]; }, # keep plains as is + + HASH => sub { $_[1]; }, # keep arrays as is + + 'IMPL::Object::List' => sub { [$_[1]->as_list()] }, # make a copy + + -default => sub { # convert to hash + my ($this,$object) = @_; + + my $propList = $this->cacheClassProps->{ref $object}; + unless ($propList) { + # derived first, then own properties, only public + my %props = map { $_->name, $_ } $this->get_meta( 'IMPL::Class::PropertyInfo', sub { $_->Access == IMPL::Class::Member::MOD_PUBLIC } , 1 ); + $this->cacheClassProps->{ref $object} = $propList = [keys %props]; + + } + + return { + map { + $_, + $this->Transform($object->$_()) + } @$propList + }; + } + } +); + +sub CTOR { + my ($this) = @_; + + $this->cacheClassProps({}); +} + +1; + +__END__ + +=pod + +=cut \ No newline at end of file