Skip to content

Commit

Permalink
Merge pull request #245 from igorkasyanchuk/243-passing-allow_blank-o…
Browse files Browse the repository at this point in the history
…ption-raises

[Validator] Better error message when using :allow_blank/nil with attached validator (#243)
  • Loading branch information
Mth0158 authored Mar 13, 2024
2 parents dd835e6 + da270af commit f738a8b
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 5 deletions.
6 changes: 3 additions & 3 deletions lib/active_storage_validations/attached_validator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,16 @@ class AttachedValidator < ActiveModel::EachValidator # :nodoc:
ERROR_TYPES = %i[blank].freeze

def check_validity!
%i(allow_nil allow_blank).each do |not_authorized_option|
%i[allow_nil allow_blank].each do |not_authorized_option|
if options.include?(not_authorized_option)
raise ArgumentError, "You cannot pass the :#{not_authorized_option} option to this validator"
raise ArgumentError, "You cannot pass the :#{not_authorized_option} option to the #{self.class.name.split('::').last.underscore}"
end
end
end

def validate_each(record, attribute, _value)
return if record.send(attribute).attached? &&
!Array.wrap(record.send(attribute)).all? { |file| file.marked_for_destruction? }
!Array.wrap(record.send(attribute)).all?(&:marked_for_destruction?)

errors_options = initialize_error_options(options)
add_error(record, attribute, ERROR_TYPES.first, **errors_options)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
# frozen_string_literal: true

module DoesNotWorkWithAllowBlankOption
extend ActiveSupport::Concern

included do
subject { validator_test_class::WithAllowBlank.new(params) }

describe 'when used with :allow_blank option' do
it { is_expected_to_raise_error(ArgumentError, "You cannot pass the :allow_blank option to this validator") }
it do
is_expected_to_raise_error(
ArgumentError,
"You cannot pass the :allow_blank option to the #{validator_test_class.name.delete('::').underscore}"
)
end
end
end
end
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
# frozen_string_literal: true

module DoesNotWorkWithAllowNilOption
extend ActiveSupport::Concern

included do
subject { validator_test_class::WithAllowNil.new(params) }

describe 'when used with :allow_nil option' do
it { is_expected_to_raise_error(ArgumentError, "You cannot pass the :allow_nil option to this validator") }
it do
is_expected_to_raise_error(
ArgumentError,
"You cannot pass the :allow_nil option to the #{validator_test_class.name.delete('::').underscore}"
)
end
end
end
end

0 comments on commit f738a8b

Please sign in to comment.