Sha256: f4ad8843e9a996a5edcce180178251cc05d98b02fcc7d16295258c516dce4d47

Contents?: true

Size: 995 Bytes

Versions: 8

Compression:

Stored size: 995 Bytes

Contents

# frozen_string_literal: true

class FileExtensionValidator < BaseValidator

  def validate_each(record, attribute, value)
    assert_valid_include_or_exclude!
    assign_attr_readers(record, attribute, value)
    valid?
  end

  private

  def assert_valid_include_or_exclude!
    return if options.key?(:include) || options.key?(:exclude)

    raise ArgumentError, 'Missing ":include" or ":exclude" attribute for comparison.'
  end

  def check
    options.key?(:exclude) ? :exclude : :include
  end

  def include_or_exclude
    values = options[:include] || options[:exclude]
    [*values]
  end

  # rubocop:disable Metrics/AbcSize
  def valid_attr?
    extension = File.extname(value.original_filename).tr('.', '')
    return false if extension.empty?

    included = include_or_exclude.any? { |ext| ext.to_s == extension }
    included = !included if check == :exclude
    return if included

    record.errors.add(attribute, *error_message)
  end
  # rubocop:enable Metrics/AbcSize

end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
lite-validators-1.0.7 lib/lite/validators/file_extension_validator.rb
lite-validators-1.0.6 lib/lite/validators/file_extension_validator.rb
lite-validators-1.0.5 lib/lite/validators/file_extension_validator.rb
lite-validators-1.0.4 lib/lite/validators/file_extension_validator.rb
lite-validators-1.0.3 lib/lite/validators/file_extension_validator.rb
lite-validators-1.0.2 lib/lite/validators/file_extension_validator.rb
lite-validators-1.0.1 lib/lite/validators/file_extension_validator.rb
lite-validators-1.0.0 lib/lite/validators/file_extension_validator.rb