From a5f03d724c1a9e59e8bb11a56e3be48ec15e6fde Mon Sep 17 00:00:00 2001 From: Alex Karle Date: Wed, 6 May 2020 00:19:30 -0400 Subject: [PATCH] lib/Euchre: Add BUILD subs to classes to de-lazify attrs No one likes a lazy "start_time" attribute ;) This is a clever hack to de-lazify them. The BUILD sub is supposed to be used for validation at object creation time, but we can just as easily use it for the instantiation of some key fields which our clients might be expecting (i.e. score needs to be present before the first round finishes). ~ckarle -- how do you like them oneline for loops :P --- lib/Euchre/Dealer.pm | 9 ++++++++- lib/Euchre/Game.pm | 8 +++++++- lib/Euchre/Host.pm | 2 -- lib/Euchre/Player.pm | 9 ++++++++- 4 files changed, 23 insertions(+), 5 deletions(-) diff --git a/lib/Euchre/Dealer.pm b/lib/Euchre/Dealer.pm index b33f083..f9be28a 100644 --- a/lib/Euchre/Dealer.pm +++ b/lib/Euchre/Dealer.pm @@ -9,12 +9,19 @@ package Euchre::Dealer; use Euchre::Errors; use Euchre::Game; -use Class::Tiny qw(id start_time), { +use Class::Tiny qw(id), { password => '', game => sub { Euchre::Game->new() }, players => sub { {} }, + start_time => sub { time }, }; +sub BUILD { + my ($self) = @_; + # de lazy the attributes + $self->$_ for qw(start_time); +} + sub add_player { my ($self, $p, $password) = @_; diff --git a/lib/Euchre/Game.pm b/lib/Euchre/Game.pm index a92ad80..7795ef4 100644 --- a/lib/Euchre/Game.pm +++ b/lib/Euchre/Game.pm @@ -18,9 +18,15 @@ use Class::Tiny qw(trump out_player turn dealer caller pass_count led trump_nomi tricks => sub { [0, 0, 0, 0] }, table => sub { [undef, undef, undef, undef] }, score => sub { $ENV{END_DEBUG} ? [9, 9] : [0, 0] }, - start_time => sub { time }, }; +sub BUILD { + # Access some of the fields so that they are present in game_state from + # the get-go (not waiting for lazy creation) + my ($self) = @_; + $self->$_ for qw(phase hands tricks table score); +} + sub next_turn { my ($self) = @_; diff --git a/lib/Euchre/Host.pm b/lib/Euchre/Host.pm index 771a5dd..51f8cf8 100644 --- a/lib/Euchre/Host.pm +++ b/lib/Euchre/Host.pm @@ -36,7 +36,6 @@ sub register_player { $PLAYERS{$id} = Euchre::Player->new( id => $id, ws => $tx, - start_time => time, ); $TOTAL_PLAYERS++; } @@ -123,7 +122,6 @@ sub join_table { if (!exists $DEALERS{$tid}) { $DEALERS{$tid} = Euchre::Dealer->new( id => $tid, - start_time => time, (exists $msg->{password} ? (password => $msg->{password}) : ()), ); $TOTAL_TABLES++; diff --git a/lib/Euchre/Player.pm b/lib/Euchre/Player.pm index ed3ccc7..52a1bc4 100644 --- a/lib/Euchre/Player.pm +++ b/lib/Euchre/Player.pm @@ -6,11 +6,18 @@ package Euchre::Player; use Euchre::Errors; -use Class::Tiny qw(id ws start_time), { +use Class::Tiny qw(id ws), { seat => -1, # spectator name => 'Anon', + start_time => sub { time }, }; +sub BUILD { + my ($self) = @_; + # de lazy the attributes + $self->$_ for qw(seat name start_time); +} + sub error { my ($self, $errno) = @_; my $json = { -- libgit2 1.1.1