Search code examples
ruby-on-railsruby-on-rails-4timercountdowntimer

How to include "Timer control" for Quiz App


I'm a newbie to Rails and I'm developing a sample application for Online Quiz.

I've developed the application successfully. Now I would like to add Timing Constraint for my application.

But, I don't know how to add timer to the questions. I browsed various blogs and I couldn't find the appropriate answer.

But I found many coding in AJAX and JavaScript for the timer.

Let me know that we can or can't able to write timer control in Ruby on rails?

I would like to get your guidence to complete my first application.


Solution

  • I had mad quiz application. My apps have a model to store timing of quiz, example :

    Quiz table attribute :
    - time -> integer
    
    Timer Table attribute :
    - start_quiz -> Datetime
    - end_quiz -> Datetime
    - end_timing_quiz -> Datetime
    - finished -> boolean
    - user_id -> integer
    - quiz_id -> integer
    

    Illustration:

    Admin make a quiz and put time to quiz (in minutes).

    When user will get quiz, calculation of time with DateTime.now and then save to end_timing_quiz

    def start_quiz
     @quiz = Quiz.find(params[:id]
     # check if user started of quiz.
     if Timer.where(:quiz_id => @quiz.id, :user_id => current_user.id).empty?
       @now = DateTime.now
       @end = @now + @quiz.time.minutes
       @time = Timer.create(:quiz_id => @quiz.id, :user_id => current_user.id, :start_quiz => @now, :end_timing_quiz => @end, :finished => false)
     else
       @time = Time.where(:quiz_id => @quiz.id, :user_id => current_user.id).first
     end
    end
    

    And on view you can using jQuery Countdown, and get end of time from @time

    <%= javascript_include_tag "countdown" %>
    
    <div class="countdown"></div>
    
    <script type="text/javascript">
    
        $(document).ready(function() {
            var date = new Date('<%= @time.end_timing_quiz %>'.replace(/\-/g,'\/').replace(/[T|Z]/g,' '));
            $('.countdown').countdown({
                until: date,
                format: 'dHMS'
            });
        });
    
    </script>
    

    So, even if user leaves the quiz or reload of browser before quiz expires, timer still countdown also user can't control of timer.