Skip to content

Commit 7392cb1

Browse files
authored
Add filename to error messages for ActiveStorage validation (#39)
1 parent 4737300 commit 7392cb1

File tree

3 files changed

+27
-3
lines changed

3 files changed

+27
-3
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
/.bundle/
2+
/vendor/bundle/
23
/.yardoc
34
/_yardoc/
45
/coverage/

lib/activestorage/validator/blob.rb

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,14 @@ def validate_each(record, attribute, values) # rubocop:disable Metrics/AbcSize
77
Array(values).each do |value|
88
if options[:size_range].present?
99
if options[:size_range].min > value.blob.byte_size
10-
record.errors.add(attribute, :min_size_error, min_size: ActiveSupport::NumberHelper.number_to_human_size(options[:size_range].min))
10+
record.errors.add(attribute, :min_size_error, min_size: ActiveSupport::NumberHelper.number_to_human_size(options[:size_range].min), filename: value.blob.filename.to_s)
1111
elsif options[:size_range].max < value.blob.byte_size
12-
record.errors.add(attribute, :max_size_error, max_size: ActiveSupport::NumberHelper.number_to_human_size(options[:size_range].max))
12+
record.errors.add(attribute, :max_size_error, max_size: ActiveSupport::NumberHelper.number_to_human_size(options[:size_range].max), filename: value.blob.filename.to_s)
1313
end
1414
end
1515

1616
unless valid_content_type?(value.blob)
17-
record.errors.add(attribute, :content_type)
17+
record.errors.add(attribute, :content_type, filename: value.blob.filename.to_s)
1818
end
1919
end
2020
end

spec/activestorage/validator/blob_spec.rb

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,4 +106,27 @@
106106
it { expect(User.new(files: [create_file_blob(filename: 'dummy.txt', content_type: 'text/plain')]).valid?).to eq false }
107107
end
108108
end
109+
110+
describe 'filename parameter in validation errors' do
111+
context 'content_type validation' do
112+
before do
113+
User.validates :file, blob: { content_type: /^image/ }
114+
User.validates :files, blob: { content_type: /^image/ }
115+
end
116+
117+
it "passes filename for has_one_attached" do
118+
user = User.new(file: create_file_blob(filename: 'dummy.txt', content_type: 'text/plain'))
119+
user.validate
120+
error_detail = user.errors.details[:file][0]
121+
expect(error_detail[:filename]).to eq('dummy.txt')
122+
end
123+
124+
it "passes filename for has_many_attached" do
125+
user = User.new(files: [create_file_blob(filename: 'dummy.txt', content_type: 'text/plain')])
126+
user.validate
127+
error_detail = user.errors.details[:files][0]
128+
expect(error_detail[:filename]).to eq('dummy.txt')
129+
end
130+
end
131+
end
109132
end

0 commit comments

Comments
 (0)