From: Matt S Trout Date: Sat, 2 Jun 2012 11:28:49 +0000 (+0000) Subject: callback calling X-Git-Tag: v0.001001~38 X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=fe6c9a7f0f8b12f9424ed3aa7ea6c4a783581ce9;p=scpubgit%2FObject-Remote.git callback calling --- diff --git a/lib/Object/Remote/CodeContainer.pm b/lib/Object/Remote/CodeContainer.pm new file mode 100644 index 0000000..948e63b --- /dev/null +++ b/lib/Object/Remote/CodeContainer.pm @@ -0,0 +1,9 @@ +package Object::Remote::CodeContainer; + +use Moo; + +has code => (is => 'ro', required => 1); + +sub call { shift->code->(@_) } + +1; diff --git a/lib/Object/Remote/Connection.pm b/lib/Object/Remote/Connection.pm index d0679c4..ea1614d 100644 --- a/lib/Object/Remote/Connection.pm +++ b/lib/Object/Remote/Connection.pm @@ -3,6 +3,7 @@ package Object::Remote::Connection; use Object::Remote::Future; use Object::Remote::Null; use Object::Remote::Handle; +use Object::Remote::CodeContainer; use Object::Remote; use IO::Handle; use Module::Runtime qw(use_module); @@ -57,17 +58,25 @@ has _json => ( }, ); +sub _id_to_remote_object { + my ($self, $id) = @_; + return bless({}, 'Object::Remote::Null') if $id eq 'NULL'; + ( + $self->remote_objects_by_id->{$id} + or Object::Remote::Handle->new(connection => $self, id => $id) + )->proxy; +} + sub _build__json { weaken(my $self = shift); - my $remotes = $self->remote_objects_by_id; JSON::PP->new->filter_json_single_key_object( __remote_object__ => sub { - my $id = shift; - return bless({}, 'Object::Remote::Null') if $id eq 'NULL'; - ( - $remotes->{$id} - or Object::Remote::Handle->new(connection => $self, id => $id) - )->proxy; + $self->_id_to_remote_object(@_); + } + )->filter_json_single_key_object( + __remote_code__ => sub { + my $code_container = $self->_id_to_remote_object(@_); + sub { $code_container->call(@_) }; } ); } @@ -165,6 +174,11 @@ sub _deobjectify { return +{ map +($_ => $self->_deobjectify($data->{$_})), keys %$data }; } elsif ($ref eq 'ARRAY') { return [ map $self->_deobjectify($_), @$data ]; + } elsif ($ref eq 'CODE') { + my $id = $self->_local_object_to_id( + Object::Remote::CodeContainer->new(code => $data) + ); + return +{ __remote_code__ => $id }; } else { die "Can't collapse reftype $ref"; } diff --git a/t/basic.t b/t/basic.t index 07d77ef..24913dc 100644 --- a/t/basic.t +++ b/t/basic.t @@ -25,4 +25,10 @@ is($remote->increment, 1, 'Increment to 1'); is($remote->counter, 1, 'Counter at 1'); +my $x = 0; + +is($remote->call_callback(27, sub { $x++ }), 27, "Callback ok"); + +is($x, 1, "Callback called callback"); + done_testing; diff --git a/t/lib/ORTestClass.pm b/t/lib/ORTestClass.pm index 7e64bf1..0751492 100644 --- a/t/lib/ORTestClass.pm +++ b/t/lib/ORTestClass.pm @@ -8,4 +8,10 @@ sub increment { $_[0]->_set_counter($_[0]->counter + 1); } sub pid { $$ } +sub call_callback { + my ($self, $value, $cb) = @_; + $cb->(); + return $value; +} + 1;