Skip to content

Instantly share code, notes, and snippets.

@samcv
Created November 26, 2016 03:40
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 samcv/2eea11092a4e2ce09269299da9327f9f to your computer and use it in GitHub Desktop.
Save samcv/2eea11092a4e2ce09269299da9327f9f to your computer and use it in GitHub Desktop.
use IRC::Client::Message;
my role perlbot-file {
has Str $.filename;
has Str $!filename-bak = $!filename ~ '.bak';
has $!file-bak-io = IO::Path.new($!filename-bak);
has %!hash;
has $!last-saved = 0;
method save ( $force? ) {
note "Entered save method for $.filename";
say "last saved is $!last-saved";
say "first" if now - $!last-saved > 100;
say "second" if $!last-saved.defined.not;
say "third" if $force;
if now - $!last-saved > 100 or $force {
my Promise $promise = start {
note "Starting to write $.filename";
try {
my $write-t1 = now;
#say colored("Trying to update $file data", 'blue');
spurt $!filename-bak, to-json( %!hash );
my $write-t2 = now;
# from-json will throw an exception if it can't process the file
# we just wrote
from-json(slurp $!filename-bak);
my $write-t3 = now;
note "Took {$write-t2 - $write-t1} to save file. Done writing $!filename";
note "Took {$write-t3 - $write-t2} to load file. Done";
CATCH { .note }
}
$!file-bak-io.copy($.filename) unless $!.defined;
$!last-saved = now;
}
return $promise;
}
Nil;
}
method load {
if $.filename.IO.e {
say "Trying to load $.filename";
my %hash;
%hash = from-json( slurp $.filename );
%!hash = %hash;
return True;
}
else {
say "Cannot find $.filename";
return False;
}
False;
}
method get-hash {
%!hash;
}
method set-hash ( %hash ) {
%!hash = %hash;
}
}
my class history-class does perlbot-file {
method add-history ( IRC::Client::Message $e ) {
my $now = now;
$!hash{$now}{'text'} = $e.text;
$!hash{$now}{'nick'} = $e.nick;
}
method add-entry ( $now, Str :$text, Str :$nick, Bool :$sed? ) {
$!hash{$now} = text => $text, nick => $nick, sed => True;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment