Skip to content

Commit

Permalink
Move submission oriented code together
Browse files Browse the repository at this point in the history
  • Loading branch information
delonnewman committed Nov 25, 2024
1 parent b951563 commit 1eaa8c0
Showing 1 changed file with 7 additions and 16 deletions.
23 changes: 7 additions & 16 deletions app/models/dragnet/reply.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,6 @@ module Dragnet
class Reply < ApplicationRecord
include Retractable

CSRF_TOKEN_PRECISION = 256
EXPIRATION_DURATION = 30.minutes # TODO: move this to configration

retract_associated :answers

belongs_to :survey, class_name: 'Dragnet::Survey'
Expand All @@ -25,9 +22,8 @@ def ensure_visit(visit)
update(ahoy_visit: visit) if visit && ahoy_visit_id != visit.id
end

# Answer caching (used for better performance in the data grid)
with AnswersCache
before_save { answers_cache.reset! }
before_save { answers_cache.set! }

def cached_answers
answers_cache.answers
Expand All @@ -38,9 +34,15 @@ def answers_to(question)
end

# Submission
CSRF_TOKEN_PRECISION = 256
EXPIRATION_DURATION = 30.minutes # TODO: move this to configration

delegate :submission_parameters, to: :survey

scope :incomplete, -> { where(submitted: false) }

validates :csrf_token, presence: true

before_validation if: :new_record? do
self.csrf_token = SecureRandom.urlsafe_base64(CSRF_TOKEN_PRECISION)
self.expires_at = EXPIRATION_DURATION.from_now
Expand All @@ -55,23 +57,12 @@ def expired?(now = Time.zone.now)
expires_at <= now
end

# Mark the reply as submitted
#
# @param [Time] timestamp
#
# @return [Reply]
def submitted!(timestamp)
self.submitted = true
self.submitted_at = timestamp
self
end

# Apply changes to attributes, validate, mark as submitted and save the reply
#
# @param [Hash{Symbol, String => Object}, ActionController::Parameters] attributes
# @param [Time] timestamp
#
# @return [Boolean]
def submit(attributes, timestamp: Time.zone.now)
assign_attributes(attributes)
validate(:submission)
Expand Down

0 comments on commit 1eaa8c0

Please sign in to comment.