Question and answer system for the web

Worth Viewing

Perl's Template Toolkit [6] helps implementing the "View" part of the Catalyst MVC. It defines a template language, which is deliberately kept simple and allows users to define dynamic fields in static HTML. Although it supports simple programming logic, such as conditions or loops, it deliberately avoids the features of a full-fledged programming language because inexperienced developers tend to add more code in the view layer, instead of relying on a clear separation of the flow controller and the view. The command

script/quizshow
create.pl view TT TT

using the included quizshow_create.pl Catalyst helper script adds the lib/QuizShow/View/TT.pm module to the directory tree created previously. The first TT represents the name of the module created here (TT.pm); the second one ensures that the latter is a class derived from the Template Toolkit View. Alternatively, Catalyst supports the Mason and HTML::Template toolkits.

Catalyst also tells the TT.pm module to  se the Template Toolkit processor to handle files ending with .tt before the web server delivers them. Figure 6 shows the quiz.tt template, which must reside in the root directory of the newly created Catalyst project.

First, the [% IF %] condition written in Template Toolkit syntax checks to see whether more questions exist. If not, the browser displays the final score, otherwise it uses the Template variables score_ok and score_nok to display the current score and the number of questions left.

The template then outputs the current question and uses the FOREACH loop to iterate through the randomly ordered answers and present them as clickable radio buttons.

The Submit button sends the web form to the web server at the original URL because the HTML doesn't specify a form URL.

Control the Flow

To define the application's control flow, you also need a Quiz.pm Controller:

script/quizshow_create.pl controller Quiz

This command line creates the lib/QuizShow/Controller/Quiz.pm file, to which you need to add the code shown in Listing 1, Ctrl-Quiz.pm.

Listing 1

Ctrl-Quiz.pm

01 #####################################
02 package QuizShow::Controller::Quiz;
03 # Mike Schilli, 2008 (m@perlmeister.com)
04 #####################################
05 use strict;
06 use warnings;
07 use base 'Catalyst::Controller';
08
09 #####################################
10 sub quiz : Global {
11 #####################################
12   my ( $self, $c, @args ) = @_;
13
14   if((@args and $args[0] eq "reset") or
15    !defined $c->session->{next_question} or
16    $c->session->{"next_question"} == -1
17     ) {
18     $c->session->{"next_question"} = 0;
19     $c->session->{"score_ok"}      = 0;
20     $c->session->{"score_nok"}     = 0;
21     $c->session->{"total"}         =
22            $c->model('Questions')->total();
23     $c->response->redirect($c->uri_for());
24     $c->detach();
25   }
26
27   if(my $answer =
28           $c->req->param("answer")) {
29
30     if($answer ==
31        $c->session()->{"correct_answer"}) {
32
33         $c->session()->{"score_ok"}++;
34     } else {
35
36         $c->session()->{"score_nok"}++;
37     }
38   }
39
40   my $next_question =
41     $c->session()->{"next_question"} || 0;
42
43   $c->stash->{template} = 'quiz.tt';
44
45   my ($question, @answers) =
46     $c->model('Questions')->
47             get_question( $next_question );
48
49   if(defined $question) {
50     @answers = map { [$_, 'incorrect'] }
51                                 @answers;
52     $answers[0]->[1] = 'correct';
53
54     my $correct_answer;
55     my $i = 0;
56
57     while (@answers) {
58       my $pick = splice(@answers,
59                         rand @answers, 1);
60       push @{ $c->stash->{answers} },
61            { text => $pick->[0],
62              num => ++$i};
63
64       $c->session()->{"correct_answer"}= $i
65           if $pick->[1] eq 'correct';
66     }
67     $c->session()->{"next_question"} =
68                         $next_question + 1;
69   } else {
70       $c->session->{next_question} = -1;
71   }
72
73   $c->stash->{question} = $question;
74
75   for(qw( total score_ok score_nok
76           next_question)) {
77     $c->stash->{ $_ } =
78         $c->session()->{ $_ };
79   }
80 }
81
82 1;

Quiz.pm defines the quiz() method, which has the :Global attribute. This allows Catalyst to catch any requests below the http://localhost:3000/quiz URL and pass any subsequent paths in to the application as the @args parameter. For example, if the user adds /quiz/reset to the URL, Catalyst calls the quiz() method and sets the first element of @args to reset.

On /reset, the quiz() resets the session data to zero and asks the browser to redirect to the application start page. This changes the URL displayed in the browser from /quiz/reset to /quiz; the controller sets the counter for right and wrong answers to 0, and a new quiz can begin.

The Catalyst object's uri_for() method generates absolute URLs from URLs entered relative to the application root, allowing the browser to redirect to them. The redirect() method itself only sets an http header, but does not interrupt the control flow; this is what makes the $c->detach() that follows in Line 24 so important.

Break the Flow

This causes Catalyst to finish processing the request. Incidentally, this is a practical method of stopping the control flow, even if you are in the middle of a nested loop construction. The $c variable points to the Catalyst system's context object; it is added to the controller's methods with the call and is useful for retrieving almost anything from the depths of the Catalyst system.

The Catalyst object's $c's session() method reveals the session hash, which is made persistent by cookies and server-side storage, including the entries next_question (index of the next question to be asked in the YAML array), score_ok (the number of questions answered correctly), score_nok (the number of questions answered incorrectly), total (total number of questions), and correct_answer to let the server know which of the randomly ordered answers is the right one for the question just posed.

Catalyst uses

$c->req->param("answer")

in line 28 to retrieve the answer form parameter provided by the browser from the request object. This number is equivalent to the number 1, 2, or 3 for the radio button clicked by the user to select an answer. If the value matches the value stored in the session hash on the server before the web page was served up, the response was correct, and the controller increments the score_ok session variable.

In line 43 the controller defines quiz.tt as the template and then stores variable values in the template stash. If the controller sets $c->stash->{score _ok}, the template processor will replace the template entry [% score_ok %] with the value determined in the controller.

Stash variables can be arbitrarily nested data structures; for example, the stash entry answers contains a pointer to an array whose elements in turn are pointers to hashes, which contain the text and number of an answer indexed by the text and num keys.

The quiz.tt template iterates over this array to display all possible answers. It assigns an alias named answer to the currently processed element and then uses [% answer.text %] and [% answer.num %] to access the underlying hash entries – that's a very practical template toolkit feature that saves a lot typing.

Lines 50 to 52 create a data structure from the answer array extracted from the YAML file. The array assigns a correct tag to the first entry, and incorrect to all others. To display the answers in random order, the while loop in line 57 picks up a random element from this array of arrays. If this is the answer tagged as correct, the controller remembers the number for the session hash later on.

Lines 60 to 62 generate a hash with the text and num entries from the answer and pushes it to the end of the answers stash. The quiz.tt template picks up the data and dynamically creates the HTML output.

Buy this article as PDF

Express-Checkout as PDF
Price $2.95
(incl. VAT)

Buy Linux Magazine

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content

comments powered by Disqus

Direct Download

Read full article as PDF:

076-080_perl.pdf  (611.30 kB)

News