euchre-live

Euchre web-app for the socially distant family
git clone git://git.alexkarle.com/euchre-live.git
Log | Files | Refs | README | LICENSE

commit a5f03d724c1a9e59e8bb11a56e3be48ec15e6fde (patch)
parent acbff37fc9a8f188b6dc956804f2985ca43ce75b
Author: Alex Karle <alex@karle.co>
Date:   Wed,  6 May 2020 00:19:30 -0400

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

Diffstat:
Mlib/Euchre/Dealer.pm | 9++++++++-
Mlib/Euchre/Game.pm | 8+++++++-
Mlib/Euchre/Host.pm | 2--
Mlib/Euchre/Player.pm | 9++++++++-
4 files changed, 23 insertions(+), 5 deletions(-)

diff --git 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 @@ -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 @@ -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 @@ -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 = {