-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlite_app
More file actions
executable file
·104 lines (84 loc) · 2.33 KB
/
Copy pathlite_app
File metadata and controls
executable file
·104 lines (84 loc) · 2.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#!/usr/bin/perl
package Moderator::Model::Question;
use Mojo::Base -base;
use DBM::Deep;
has db => sub {
my $self = shift;
return $self->{db} ||= DBM::Deep->new("lite_app.db");
};
sub add {
my ($self, $question) = @_;
my $id = time.$$;
$self->db->{$id} = {question => [$question, time], rank => 1};
return $id;
}
sub delete_question {
my ($self, $id) = @_;
delete $self->db->{$id};
}
sub vote {
my ($self, $id, $vote) = @_;
return unless $vote;
if ( $vote eq 'up' ) {
$self->db->{$id}->{rank}++;
} elsif ( $vote eq 'down' ) {
$self->db->{$id}->{rank}--;
}
return $self->db->{$id}->{rank};
}
sub answer {
my ($self, $id, $answer) = @_;
return unless $answer;
$self->db->{$id}->{answer} = [$answer, time];
}
sub add_comment {
my ($self, $id, $comment) = @_;
return unless $comment;
push @{$self->db->{$id}->{comment}}, [$comment, time];
}
sub show {
my ($self, $id) = @_;
if ( $id ) {
$self->db->export->{$id};
} else {
my $q = $self->db->export;
return [map { [$_ => $q->{$_}] } sort { $q->{$b}->{rank} <=> $q->{$a}->{rank} } keys %$q];
}
}
package main;
use Mojolicious::Lite;
plugin 'AssetPack';
app->asset('nemo.js' => 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js');
#app->asset('begl.css' => 'css/normalize.css', 'css/main.css');
helper question => sub { state $nemo = Moderator::Model::Question->new };
get '/' => sub {
my $c = shift;
$c->render('index', questions => $c->question->show);
};
post '/questions/:id' => {id => ''} => sub {
my $c = shift;
my $id;
if ( $id = $c->param('id') ) {
$c->question->vote($id, $c->param('vote'));
$c->question->answer($id, $c->param('answer'));
$c->question->add_comment($id, $c->param('comment'));
} else {
$id = $c->question->add($c->param('question'));
}
$c->render(json => $c->question->show($id));
} => 'q';
del '/questions/delete/:id' => sub {
my $c = shift;
$c->question->delete_question($id);
$c->render(json => {ok => 'true'});
}
app->start;
__DATA__
@@ index1.html.ep
% foreach ( @$questions ) {
<%= $_->[1]->{question}->[0] %> / <%= $_->[1]->{rank} %> / <%= link_to Up => 'q', {id => $_->[0], vote => 'up'} %> / <%= link_to Down => 'q', {id => $_->[0], vote => 'down'} %><br />
% }
<form>
<input type="text" name="question" />
<button name="submit" value="Submit" />
</form>