2021-12-05 04:06:05 +00:00
|
|
|
#!/usr/bin/env perl
|
|
|
|
|
|
|
|
package GuestbookNg::Model::Message;
|
|
|
|
|
|
|
|
use Mojo::Base -base, -signatures;
|
|
|
|
|
|
|
|
has 'pg';
|
|
|
|
|
2021-12-12 06:50:07 +00:00
|
|
|
sub new($class, $pg, $pg_object) {
|
|
|
|
bless {
|
|
|
|
$pg => $pg_object,
|
|
|
|
max_posts => 5
|
|
|
|
}
|
2021-12-05 04:06:05 +00:00
|
|
|
}
|
|
|
|
|
2021-12-05 07:52:31 +00:00
|
|
|
sub get_posts($self) {
|
2021-12-22 04:57:48 +00:00
|
|
|
$self->pg->db->query(<<~'END_SQL')->arrays()
|
|
|
|
SELECT to_char(message_date, 'Dy Mon DD HH:MI:SS AM TZ YYYY'),
|
|
|
|
visitor_name,
|
|
|
|
message
|
|
|
|
FROM messages
|
|
|
|
ORDER BY message_date DESC;
|
|
|
|
END_SQL
|
2021-12-05 07:52:31 +00:00
|
|
|
}
|
|
|
|
|
2021-12-20 00:09:16 +00:00
|
|
|
sub create_post($self, $name, $message) {
|
2021-12-23 02:03:51 +00:00
|
|
|
$self->pg->db->query(<<~'END_SQL', $name, $message)
|
2021-12-22 04:57:48 +00:00
|
|
|
INSERT INTO messages (message_date, visitor_name, message)
|
|
|
|
VALUES (NOW(), ?, ?);
|
|
|
|
END_SQL
|
2021-12-05 07:52:31 +00:00
|
|
|
}
|
|
|
|
|
2021-12-19 22:43:58 +00:00
|
|
|
sub view_posts($self, $this_page, $last_page = undef, @posts) {
|
|
|
|
$last_page //= get_last_page(@posts);
|
|
|
|
|
2021-12-12 06:50:07 +00:00
|
|
|
my $last_post = $this_page * $self->{'max_posts'} - 1;
|
|
|
|
my $first_post = $last_post - $self->{'max_posts'} + 1;
|
|
|
|
|
|
|
|
grep defined, @posts[$first_post..$last_post];
|
|
|
|
}
|
|
|
|
|
|
|
|
sub max_posts($self, $value = undef) {
|
2021-12-22 04:09:35 +00:00
|
|
|
$self->{'max_posts'} = $value // $self->{'max_posts'}
|
2021-12-12 06:50:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
sub get_last_page($self, @posts) {
|
2021-12-19 04:03:53 +00:00
|
|
|
# Add a page if we have "remainder" posts
|
|
|
|
if (scalar(@posts) % $self->{'max_posts'}) {
|
|
|
|
sprintf('%d', scalar(@posts) / $self->{'max_posts'}) + 1
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
sprintf('%d', scalar(@posts) / $self->{'max_posts'})
|
|
|
|
}
|
2021-12-12 06:50:07 +00:00
|
|
|
}
|
|
|
|
|
2021-12-05 04:06:05 +00:00
|
|
|
1;
|