a11yist/app/models/element.rb
david c36230b8ba
Some checks failed
/ Run tests (push) Successful in 2m6s
/ Run system tests (push) Failing after 2m29s
/ Build, push and deploy image (push) Successful in 1m46s
edit comment and pdf export
2024-11-23 21:11:01 +01:00

59 lines
1.7 KiB
Ruby

# frozen_string_literal: true
class Element < ApplicationRecord
has_rich_text :description
belongs_to :page, touch: true
has_many :success_criteria, -> { order(:position) }, dependent: :destroy
delegate :report, to: :page
before_validation :set_position
before_update :update_positions, if: :position_changed?
has_one_attached :screenshot do |attachable|
attachable.variant :thumbnail, resize_to_limit: [ 200, 200 ]
end
scope :failed, -> { where(SuccessCriterion.where(result: SuccessCriterion.results[:failed]).arel.exists) }
# Calculate actual conformity level:
# - if a success_criterion has result :failed -> the confirmity_level
# of that success_criterion is not reached.
# - the resulting level is the highest readched level
# abeying rule above.
def level
return nil
return nil unless success_criteria.all(&:result)
element
min_failed = success_criteria.select(&:failed?).map(&:level).min
possible_levels = success_criteria.select(&:passed?).map(&:level).uniq
return nil if possible_levels.empty?
Rails.logger.debug possible_levels.inspect
Rails.logger.debug min_failed
possible_levels[possible_levels.find_index(min_failed) - 1]
end
def max_level
@max_level ||= success_criteria.reject(&:not_applicable?).max(&:level)
end
def number
"#{page.position}.#{position}"
end
private
def set_position
Rails.logger.debug("element: position #{position}")
self.position ||= (page.elements.pluck(:position).max || 0) + 1
end
def update_positions
if position_was
page.elements.where("position > ?", position_was).update_all("position = position - 1")
end
page.elements.where(position: position..).update_all("position = position + 1")
end
end