add automatic proxy system for passing objects to Template::Toolkit

This commit is contained in:
Graham Knop 2011-06-15 18:19:16 -05:00
parent 6dfeb6ef1a
commit 0a09ea4895
4 changed files with 187 additions and 47 deletions

View file

@ -1,6 +1,7 @@
package WebGUI::Template::Plugin::Asset;
use base 'Template::Plugin';
use WebGUI::Template::Proxy::Asset;
sub new {
my $config = ref($_[-1]) eq 'HASH' ? pop(@_) : { };
@ -9,42 +10,33 @@ sub new {
my $stash = $context->stash;
my $session = $stash->{_session};
my $self = bless {
_session => $session,
_context => $context,
}, $class;
if ( ref $asset) {
}
elsif ( defined $asset ) {
$asset = $self->_getAsset($asset);
$asset = $class->_getAsset($session, $asset);
}
elsif ( $stash->{_asset} ) {
$asset = $stash->{_asset};
}
elsif ( $stash->{assetId} ) {
$asset = $self->_getAsset($stash->{assetId});
$asset = $class->_getAsset($session, $stash->{assetId});
}
else {
$asset = $session->asset;
}
$self->{_asset} = $asset;
my %properties = map { $_ => 1 } $asset->meta->get_all_properties_list;
$self->{_callable} = \%properties;
return $self;
return WebGUI::Template::Proxy::Asset->_new($context, $asset);
}
sub _getAsset {
my ( $self, $id ) = @_;
my ( $class, $session, $id ) = @_;
my ( $asset );
try {
$asset = WebGUI::Asset->newByUrl( $self->session, $id );
$asset = WebGUI::Asset->newByUrl( $session, $id );
}
catch {
try {
$asset = WebGUI::Asset->newById( $self->session, $id );
$asset = WebGUI::Asset->newById( $session, $id );
}
catch {
die "Could not find asset $id to include in template: " . $_;
@ -53,37 +45,5 @@ sub _getAsset {
return $asset;
}
sub DESTROY {
# prevent AUTOLOADing
}
sub AUTOLOAD {
my $sub = our $AUTOLOAD;
$sub =~ s/.*:://;
my $self = shift;
if ($self->{_callable}{$sub}) {
my $result = $self->{_asset}->();
if ( eval { $result->isa('WebGUI::Asset'); 1 } ) {
return $self->_wrap($result);
}
return $result;
}
die 'Not allowed to call ' . $sub;
}
sub _wrap {
my $self = shift;
my $wrap = shift;
my $class = ref $self;
return $class->new($self->{_context}, $wrap);
}
sub parent {
my $self = shift;
my $parent = $self->{_asset}->parentNode;
return $self->_wrap($parent);
}
1;