All basic question types

This commit is contained in:
Charlotte Van Petegem 2025-04-27 00:13:20 +02:00
parent 3e1e5618ca
commit 4fe218166f
Signed by: chvp
SSH key fingerprint: SHA256:s9rb8jBVfdahqWHuBAcHCBP1wmj4eYQXZfqgz4H3E9E
51 changed files with 760 additions and 92 deletions

View file

@ -1,4 +1,16 @@
class ApplicationController < ActionController::Base
# Only allow modern browsers supporting webp images, web push, badges, import maps, CSS nesting, and CSS :has.
allow_browser versions: :modern
before_action :require_authorization
def authorized?
cookies.signed[:_entrance_exam_authorized].present?
end
private
def require_authorization
redirect_to new_sessions_path unless authorized?
end
end

View file

@ -0,0 +1,23 @@
class QuestionsController < ApplicationController
def answer
question = Question.find(params[:id])
@answer = Answer.find_or_initialize_by(question:)
send(:"handle_#{question.answer_kind}_answer")
end
private
def handle_simple_answer
@answer.update!(data: params[:value])
end
def handle_image_answer
@answer.image.attach(
io: StringIO.new(Base64.decode64(params[:data])),
filename: params[:filename],
content_type: params[:mimetype],
)
@answer.save!
end
end

View file

@ -0,0 +1,10 @@
class SectionsController < ApplicationController
def index
@sections = Section.all
end
def show
@section = Section.find(params[:id])
@questions = @section.questions.includes(:answer)
end
end

View file

@ -0,0 +1,25 @@
class SessionsController < ApplicationController
skip_before_action :require_authorization
def new
redirect_to sections_path if authorized?
end
def create
if authorized?
redirect_to sections_path
return
end
if Rails.configuration.entrance_exam_token != params[:token]
redirect_to new_sessions_path
return
end
cookies.signed[:_entrance_exam_authorized] = {
value: true,
expires: 1.year
}
redirect_to sections_path
end
end

View file

@ -0,0 +1,2 @@
module QuestionsHelper
end

View file

@ -0,0 +1,2 @@
module SectionsHelper
end

View file

@ -0,0 +1,2 @@
module SessionsHelper
end

View file

@ -1 +1,8 @@
// Entry point for the build script in your package.json
import initSimpleQuestions from './simple_input.js'
import initImageQuestions from './image_input.js'
addEventListener("DOMContentLoaded", () => {
initSimpleQuestions()
initImageQuestions()
})

View file

@ -0,0 +1,35 @@
const csrfToken = document.querySelector("[name='csrf-token']").content
export default function initImageQuestions() {
document.querySelectorAll('[data-behaviour="question_image_input"]').forEach((input) => {
const submitUrl = input.dataset.submitUrl
input.addEventListener('change', () => {
const file = input.files[0];
const fileReader = new FileReader();
fileReader.onload = (ev) => {
fetch(submitUrl, {
method: 'PUT',
headers: {
"x-csrf-token": csrfToken,
"content-type": "application/json",
},
body: JSON.stringify({
filename: file.name,
mimetype: file.type,
data: ev.target.result.replace(/^data:[a-zA-Z0-9!#$%^&\\*_\-+{}|'.`~]+\/[a-zA-Z0-9!#$%^&\\*_\-+{}|'.`~]+;base64,/, ""),
})
})
}
fileReader.readAsDataURL(file);
const preview = document.querySelector(`#${input.id}_preview`)
while (preview.firstChild) {
preview.removeChild(preview.firstChild)
}
const previewImage = document.createElement("img")
previewImage.src = URL.createObjectURL(file)
previewImage.alt = previewImage.title = file.name
preview.appendChild(previewImage)
})
})
}

View file

@ -0,0 +1,23 @@
import debounce from 'debounce'
const csrfToken = document.querySelector("[name='csrf-token']").content
export default function initSimpleQuestions() {
document.querySelectorAll('[data-behaviour="question_simple_input"]').forEach((input) => {
const submitUrl = input.dataset.submitUrl
const handleInput = debounce(() => {
fetch(submitUrl, {
method: 'PUT',
headers: {
"x-csrf-token": csrfToken,
"content-type": "application/json",
},
body: JSON.stringify({ value: input.value }),
})
}, 300)
input.addEventListener('change', handleInput)
input.addEventListener('input', handleInput)
})
}

View file

@ -1,3 +1,25 @@
# == Schema Information
#
# Table name: answers
#
# id :integer not null, primary key
# data :text
# created_at :datetime not null
# updated_at :datetime not null
# question_id :integer not null
#
# Indexes
#
# index_answers_on_question_id (question_id)
#
# Foreign Keys
#
# question_id (question_id => questions.id)
#
class Answer < ApplicationRecord
belongs_to :question
has_one_attached :image
serialize :data, coder: JSON
end

View file

@ -1,3 +1,28 @@
# == Schema Information
#
# Table name: questions
#
# id :integer not null, primary key
# answer_kind :integer not null
# public_asset_path :string
# question_kind :integer default("simple"), not null
# text :text not null
# created_at :datetime not null
# updated_at :datetime not null
# section_id :integer not null
#
# Indexes
#
# index_questions_on_section_id (section_id)
#
# Foreign Keys
#
# section_id (section_id => sections.id)
#
class Question < ApplicationRecord
enum :answer_kind, { simple: 0, image: 1, politicians: 2 }, prefix: true
enum :question_kind, { simple: 0, video: 1 }, prefix: true
belongs_to :section
has_one :answer
end

View file

@ -1,2 +1,13 @@
# == Schema Information
#
# Table name: sections
#
# id :integer not null, primary key
# description :text not null
# title :text not null
# created_at :datetime not null
# updated_at :datetime not null
#
class Section < ApplicationRecord
has_many :questions
end

View file

@ -3,23 +3,18 @@
<head>
<title><%= content_for(:title) || "Entrance Exam" %></title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="mobile-web-app-capable" content="yes">
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= yield :head %>
<%# Enable PWA manifest for installable apps (make sure to enable in config/routes.rb too!) %>
<%#= tag.link rel: "manifest", href: pwa_manifest_path(format: :json) %>
<link rel="icon" href="/icon.png" type="image/png">
<link rel="icon" href="/icon.svg" type="image/svg+xml">
<link rel="apple-touch-icon" href="/icon.png">
<%# Includes all stylesheet files in app/assets/stylesheets %>
<%= stylesheet_link_tag :app %>
<%= javascript_include_tag "application", "data-turbo-track": "reload", type: "module" %>
<%= javascript_include_tag "application" %>
</head>
<body>

View file

@ -1,22 +0,0 @@
{
"name": "EntranceExam",
"icons": [
{
"src": "/icon.png",
"type": "image/png",
"sizes": "512x512"
},
{
"src": "/icon.png",
"type": "image/png",
"sizes": "512x512",
"purpose": "maskable"
}
],
"start_url": "/",
"display": "standalone",
"scope": "/",
"description": "EntranceExam.",
"theme_color": "red",
"background_color": "red"
}

View file

@ -1,26 +0,0 @@
// Add a service worker for processing Web Push notifications:
//
// self.addEventListener("push", async (event) => {
// const { title, options } = await event.data.json()
// event.waitUntil(self.registration.showNotification(title, options))
// })
//
// self.addEventListener("notificationclick", function(event) {
// event.notification.close()
// event.waitUntil(
// clients.matchAll({ type: "window" }).then((clientList) => {
// for (let i = 0; i < clientList.length; i++) {
// let client = clientList[i]
// let clientPath = (new URL(client.url)).pathname
//
// if (clientPath == event.notification.data.path && "focus" in client) {
// return client.focus()
// }
// }
//
// if (clients.openWindow) {
// return clients.openWindow(event.notification.data.path)
// }
// })
// )
// })

View file

@ -0,0 +1,12 @@
<div id="<%= "question_answer_#{question.id}_preview" %>">
<% if question.answer.present? %>
<%= image_tag question.answer.image %>
<% end %>
</div>
<input id="<%= "question_answer_#{question.id}" %>"
type="file"
accept=".jpg,.jpeg,.png,.webp,image/jpg,image/jpeg,image/png,image/webp"
autocomplete="off"
data-behaviour="question_image_input"
data-submit-url="<%= answer_question_url(question.id) %>"
/>

View file

@ -0,0 +1,3 @@
<div>
This one's going to be hard...
</div>

View file

@ -0,0 +1,7 @@
<input id="<%= "question_answer_#{question.id}" %>"
type="text"
value="<%= question.answer&.data || '' %>"
autocomplete="off"
data-behaviour="question_simple_input"
data-submit-url="<%= answer_question_url(question.id) %>"
/>

View file

@ -0,0 +1 @@
<%= question.text %>

View file

@ -0,0 +1 @@
<video src="<%= question.public_asset_path %>" controls preload="metadata"></video>

View file

@ -0,0 +1,5 @@
<% @sections.each do |section| %>
<p>
<%= link_to section.title, section_url(section) %>
</p>
<% end %>

View file

@ -0,0 +1,10 @@
<h4><%= @section.title %></h4>
<p><%= @section.description %></p>
<% @questions.each do |question| %>
<section>
<%= render partial: "questions/#{question.question_kind}_show", locals: { question: } %>
<%= render partial: "questions/#{question.answer_kind}_form", locals: { question: } %>
</section>
<% end %>

View file

@ -0,0 +1,5 @@
<%= form_with url: sessions_path, method: :post do |form| %>
<%= form.label :token, "Token" %>
<%= form.password_field :token %>
<%= form.submit "Start exam" %>
<% end %>