Skip to content

Instantly share code, notes, and snippets.

/json.diff Secret

Created March 25, 2016 23:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/200b3b2a0514957ba6c4 to your computer and use it in GitHub Desktop.
Save anonymous/200b3b2a0514957ba6c4 to your computer and use it in GitHub Desktop.
diff --git a/lib/Mojo/Pg/PubSub.pm b/lib/Mojo/Pg/PubSub.pm
index 4098076..5b225bb 100644
--- a/lib/Mojo/Pg/PubSub.pm
+++ b/lib/Mojo/Pg/PubSub.pm
@@ -1,10 +1,17 @@
package Mojo::Pg::PubSub;
use Mojo::Base 'Mojo::EventEmitter';
+use Mojo::JSON qw(from_json to_json);
use Scalar::Util 'weaken';
has 'pg';
+sub json {
+ my $self = shift;
+ $self->{json}{$_}++ for @_;
+ return $self;
+}
+
sub listen {
my ($self, $name, $cb) = @_;
$self->_db->listen($name) unless @{$self->{chans}{$name} ||= []};
@@ -12,7 +19,7 @@ sub listen {
return $cb;
}
-sub notify { $_[0]->_db->notify(@_[1, 2]) and return $_[0] }
+sub notify { $_[0]->_db->notify(_json(@_)) and return $_[0] }
sub unlisten {
my ($self, $name, $cb) = @_;
@@ -37,6 +44,7 @@ sub _db {
$db->on(
notification => sub {
my ($db, $name, $pid, $payload) = @_;
+ $payload = from_json $payload if $self->{json}{$name};
for my $cb (@{$self->{chans}{$name}}) { $self->$cb($payload) }
}
);
@@ -52,6 +60,8 @@ sub _db {
return $db;
}
+sub _json { $_[1], $_[0]{json}{$_[1]} ? to_json $_[2] : $_[2] }
+
1;
=encoding utf8
@@ -110,6 +120,21 @@ L<Mojo::Pg> object this publish/subscribe container belongs to.
L<Mojo::Pg::PubSub> inherits all methods from L<Mojo::EventEmitter> and
implements the following new ones.
+=head2 json
+
+ $pubsub = $pubsub->json('foo', 'bar');
+
+Activate JSON encoding/decoding for these channels with L<Mojo::JSON/"to_json">
+and L<Mojo::JSON/"from_json"> for notifications sent with L</"notify"> or
+received with L</"listen">.
+
+ # Send and receive data structures
+ $pubsub->json('foo')->listen(foo => sub {
+ my ($pubsub, $payload) = @_;
+ say $payload->{bar};
+ });
+ $pubsub->notify(foo => {bar => 'I ♥ Mojolicious!'});
+
=head2 listen
my $cb = $pubsub->listen(foo => sub {...});
@@ -131,6 +156,7 @@ have.
$pubsub = $pubsub->notify('foo');
$pubsub = $pubsub->notify(foo => 'I ♥ Mojolicious!');
+ $pubsub = $pubsub->notify(foo => {bar => 'baz'});
Notify a channel.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment