DUMMY.pm 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package Trog::Data::DUMMY;
  2. use strict;
  3. use warnings;
  4. no warnings 'experimental';
  5. use feature qw{signatures};
  6. use Carp qw{confess};
  7. use JSON::MaybeXS;
  8. use File::Slurper;
  9. use File::Copy;
  10. use Mojo::File;
  11. use List::Util;
  12. use parent qw{Trog::DataModule};
  13. =head1 WARNING
  14. Do not use this as a production data model. It is *not* safe to race conditions, and is only here for testing.
  15. =cut
  16. our $datastore = 'data/DUMMY.json';
  17. sub lang { 'Perl Regex in Quotemeta' }
  18. sub help { 'https://perldoc.perl.org/functions/quotemeta.html' }
  19. our $posts;
  20. sub read ($self, $query=undef) {
  21. confess "Can't find datastore!" unless -f $datastore;
  22. my $slurped = File::Slurper::read_text($datastore);
  23. $posts = JSON::MaybeXS::decode_json($slurped);
  24. return $posts;
  25. }
  26. sub count ($self) {
  27. $posts //= $self->read();
  28. return scalar(@$posts);
  29. }
  30. sub write($self,$data) {
  31. open(my $fh, '>', $datastore) or confess;
  32. print $fh JSON::MaybeXS::encode_json($data);
  33. close $fh;
  34. }
  35. sub delete($self, @posts) {
  36. my $example_posts = $self->read();
  37. foreach my $update (@posts) {
  38. @$example_posts = grep { $_->{id} ne $update->{id} } @$example_posts;
  39. }
  40. $self->write($example_posts);
  41. return 0;
  42. }
  43. 1;