guestbook-ng/lib/GuestbookNg/Model/Message.pm

65 lines
1.7 KiB
Perl
Raw Normal View History

2021-12-04 23:06:05 -05:00
#!/usr/bin/env perl
package GuestbookNg::Model::Message;
use Mojo::Base -base, -signatures;
has 'pg';
2021-12-12 01:50:07 -05:00
sub new($class, $pg, $pg_object) {
bless {
$pg => $pg_object,
max_posts => 5
}
2021-12-04 23:06:05 -05:00
}
2021-12-22 22:23:10 -05:00
sub get_posts($self, $this_page = undef) {
if ($this_page) {
my $row_count = $self->{'max_posts'};
2021-12-25 01:46:39 -05:00
my $offset = ($this_page - 1) * $row_count;
2021-12-22 22:23:10 -05:00
$self->pg->db->query(<<~'END_SQL', $row_count, $offset)->arrays();
SELECT to_char(message_date, 'Dy Mon DD HH:MI:SS AM TZ YYYY'),
visitor_name,
message
2021-12-30 21:39:16 -05:00
FROM guestbook
2021-12-22 22:23:10 -05:00
ORDER BY message_date DESC
LIMIT ? OFFSET ?;
END_SQL
}
else {
$self->pg->db->query(<<~'END_SQL')->arrays()
SELECT to_char(message_date, 'Dy Mon DD HH:MI:SS AM TZ YYYY'),
visitor_name,
message
2021-12-30 21:39:16 -05:00
FROM guestbook
2021-12-22 22:23:10 -05:00
ORDER BY message_date DESC;
END_SQL
}
}
2021-12-19 19:09:16 -05:00
sub create_post($self, $name, $message) {
2021-12-22 21:03:51 -05:00
$self->pg->db->query(<<~'END_SQL', $name, $message)
2021-12-30 21:39:16 -05:00
INSERT INTO guestbook (message_date, visitor_name, message)
2021-12-21 23:57:48 -05:00
VALUES (NOW(), ?, ?);
END_SQL
}
2021-12-12 01:50:07 -05:00
sub max_posts($self, $value = undef) {
2021-12-21 23:09:35 -05:00
$self->{'max_posts'} = $value // $self->{'max_posts'}
2021-12-12 01:50:07 -05:00
}
2021-12-22 22:23:10 -05:00
sub get_last_page($self) {
2021-12-25 01:46:39 -05:00
my $post_count = $self->get_post_count();
my $last_page = sprintf('%d', $post_count / $self->{'max_posts'});
2021-12-22 22:23:10 -05:00
2021-12-18 23:03:53 -05:00
# Add a page if we have "remainder" posts
2021-12-25 01:46:39 -05:00
return $post_count % $self->{'max_posts'} ? ++$last_page : $last_page;
2021-12-12 01:50:07 -05:00
}
2021-12-22 22:23:10 -05:00
sub get_post_count($self) {
2021-12-30 21:39:16 -05:00
$self->pg->db->query('SELECT count(*) FROM guestbook;')->text()
2021-12-22 22:23:10 -05:00
}
2021-12-04 23:06:05 -05:00
1;