class PuzzlesController < ApplicationController before_action :prepare_session def about @normal_puzzle = Puzzle.normal.order(created_at: :desc).first if session[:puzzles]["normal"]["id"] == @normal_puzzle.id @normal_started = session[:puzzles]["normal"]["started"] @normal_solved = session[:puzzles]["normal"]["solved"] else @normal_started = false @normal_solved = false end @hard_puzzle = Puzzle.hard.order(created_at: :desc).first if session[:puzzles]["hard"]["id"] == @hard_puzzle.id @hard_started = session[:puzzles]["hard"]["started"] @hard_solved = session[:puzzles]["hard"]["solved"] else @hard_started = false @hard_solved = false end @expert_puzzle = Puzzle.expert.order(created_at: :desc).first if session[:puzzles]["expert"]["id"] == @expert_puzzle.id @expert_started = session[:puzzles]["expert"]["started"] @expert_solved = session[:puzzles]["expert"]["solved"] else @expert_started = false @expert_solved = false end end def index @puzzles = Puzzle.select(:id, :created_at, :category).order(created_at: :asc).all.chunk { |puzzle| puzzle.created_at.localtime.to_date }.to_h.transform_values { |by_date| by_date.sort_by(&:category).chunk { |puzzle| puzzle.category }.to_h } end def show @puzzle = Puzzle.find(params["id"]) if @puzzle.latest? if session[:puzzles][@puzzle.category]["id"] == @puzzle.id @playable = !(session[:puzzles][@puzzle.category]["solved"]) @already_started = session[:puzzles][@puzzle.category]["started"] unless @playable @solution = session[:puzzles][@puzzle.category]["path"] end else @playable = true @already_started = false end else @playable = false @already_started = false @solution = @puzzle.solved_data end end def start @puzzle = Puzzle.find(params["id"]) if session[:puzzles][@puzzle.category]["id"] != @puzzle.id session[:puzzles][@puzzle.category] = { "id" => @puzzle.id } end session[:puzzles][@puzzle.category]["started"] = true end def solve @puzzle = Puzzle.find(params["id"]) raise ActiveRecord::RecordNotFound unless @puzzle.latest? if @puzzle.solved_data.nil? @puzzle.solved_data = params["solved"] @puzzle.save! end @time = (params.include? :time) ? params[:time] : nil if session[:puzzles][@puzzle.category]["id"] != @puzzle.id session[:puzzles][@puzzle.category] = { "id" => @puzzle.id } end session[:puzzles][@puzzle.category]["solved"] = true session[:puzzles][@puzzle.category]["path"] = params["solved"] end def submit @puzzle = Puzzle.find(params["id"]) raise ActiveRecord::RecordNotFound unless @puzzle.latest? @puzzle.scores.create(name: params[:name], ip: request.ip, seconds_taken: (params.include? :time) ? params[:time] : nil) redirect_to @puzzle end private def prepare_session session[:puzzles] ||= { normal: { "id" => 0 }, hard: { "id" => 0 }, expert: { "id" => 0 }, } end end