You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
2.4 KiB

  1. # frozen_string_literal: true
  2. # Monkey-patch various Paperclip validators for Ruby 3.0 compatibility
  3. module Paperclip
  4. module Validators
  5. module AttachmentSizeValidatorExtensions
  6. def validate_each(record, attr_name, _value)
  7. base_attr_name = attr_name
  8. attr_name = "#{attr_name}_file_size".to_sym
  9. value = record.send(:read_attribute_for_validation, attr_name)
  10. if value.present?
  11. options.slice(*Paperclip::Validators::AttachmentSizeValidator::AVAILABLE_CHECKS).each do |option, option_value|
  12. option_value = option_value.call(record) if option_value.is_a?(Proc)
  13. option_value = extract_option_value(option, option_value)
  14. next if value.send(Paperclip::Validators::AttachmentSizeValidator::CHECKS[option], option_value)
  15. error_message_key = options[:in] ? :in_between : option
  16. [attr_name, base_attr_name].each do |error_attr_name|
  17. record.errors.add(error_attr_name, error_message_key, **filtered_options(value).merge(
  18. min: min_value_in_human_size(record),
  19. max: max_value_in_human_size(record),
  20. count: human_size(option_value)
  21. ))
  22. end
  23. end
  24. end
  25. end
  26. end
  27. module AttachmentContentTypeValidatorExtensions
  28. def mark_invalid(record, attribute, types)
  29. record.errors.add attribute, :invalid, **options.merge({ types: types.join(', ') })
  30. end
  31. end
  32. module AttachmentPresenceValidatorExtensions
  33. def validate_each(record, attribute, _value)
  34. if record.send("#{attribute}_file_name").blank?
  35. record.errors.add(attribute, :blank, **options)
  36. end
  37. end
  38. end
  39. module AttachmentFileNameValidatorExtensions
  40. def mark_invalid(record, attribute, patterns)
  41. record.errors.add attribute, :invalid, options.merge({ names: patterns.join(', ') })
  42. end
  43. end
  44. end
  45. end
  46. Paperclip::Validators::AttachmentSizeValidator.prepend(Paperclip::Validators::AttachmentSizeValidatorExtensions)
  47. Paperclip::Validators::AttachmentContentTypeValidator.prepend(Paperclip::Validators::AttachmentContentTypeValidatorExtensions)
  48. Paperclip::Validators::AttachmentPresenceValidator.prepend(Paperclip::Validators::AttachmentPresenceValidatorExtensions)
  49. Paperclip::Validators::AttachmentFileNameValidator.prepend(Paperclip::Validators::AttachmentFileNameValidatorExtensions)