Skip to content

Commit

Permalink
add file size to validation tracking
Browse files Browse the repository at this point in the history
  • Loading branch information
asmega committed Dec 1, 2023
1 parent 2056be4 commit 5e2d6db
Show file tree
Hide file tree
Showing 4 changed files with 82 additions and 1 deletion.
14 changes: 14 additions & 0 deletions app/lib/upload_wrapper.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
class UploadWrapper
include ActiveSupport::NumberHelper

attr_reader :upload

def initialize(upload:)
@upload = upload
end

def as_json(*args)
r = super
r.merge(file_size: number_to_human_size(upload.size, strip_insignificant_zeros: false))
end
end
14 changes: 13 additions & 1 deletion app/models/concerns/validation_tracking.rb
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,18 @@ def value_for_field(field)
return if field == :base
return if field.to_s.start_with?("section.")

public_send(field)
value = public_send(field)

if value.instance_of?(Array)
value = value.map do |upload|
if upload.instance_of?(ActionDispatch::Http::UploadedFile)
UploadWrapper.new(upload:)
else
upload
end
end
end

value
end
end
15 changes: 15 additions & 0 deletions spec/lib/upload_wrapper_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
require "rails_helper"

RSpec.describe UploadWrapper do
describe "#as_json" do
subject(:upload_wrapper) do
described_class.new(upload:)
end

let(:upload) { file_fixture("upload1.pdf") }

it "includes file size" do
expect(upload_wrapper.as_json[:file_size]).to eql("4.98 KB")
end
end
end
40 changes: 40 additions & 0 deletions spec/models/concerns/validation_tracking_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
require "rails_helper"

RSpec.describe ValidationTracking do
let(:klass) do
Class.new do
include ActiveModel::Model
include ValidationTracking

attr_accessor :evidence_uploads

validate :field_with_meta_options

def self.model_name
ActiveModel::Name.new(self, nil, "referrals/allegation_evidence/upload_form")
end

def self.name
"Referrals::AllegationEvidence::UploadForm"
end

def field_with_meta_options
errors.add(:evidence_uploads, :file_size_too_big, max_allowed_file_size: "50MB")
end
end
end

describe "#track_validation_error" do
context "when an uploaded file" do
it "persists the file size" do
instance = klass.new(evidence_uploads: [ActionDispatch::Http::UploadedFile.new(tempfile: file_fixture("upload1.pdf"))])

expect do
instance.valid?
end.to change(ValidationError, :count).by(1)

expect(ValidationError.last.details.dig("evidence_uploads", "value", 0, "file_size")).to eql("4.98 KB")
end
end
end
end

0 comments on commit 5e2d6db

Please sign in to comment.