Sha256: 386f438b9e8c1ae4f66660354f7348ed5c51efa5a76030912e91128f0111b529

Contents?: true

Size: 1.09 KB

Versions: 13

Compression:

Stored size: 1.09 KB

Contents

# frozen_string_literal: true

class BaseValidator < ActiveModel::EachValidator

  def validate_each(record, attribute, value)
    assign_attr_readers(record, attribute, value)
    return if valid?

    record.errors.add(attribute, *error_message)
  end

  private

  attr_reader :record, :attribute, :value

  def assign_attr_readers(record, attribute, value)
    @record = record
    @attribute = attribute
    @value = value
  end

  # rubocop:disable Layout/LineLength
  def assert_valid_option!(name, collection, option: nil)
    option ||= send(name)

    Array(option).each do |option_value|
      next if collection.include?(option_value)

      raise ArgumentError, "Unknown #{name}: #{option_value.inspect}. Valid options are: #{collection.map(&:inspect).join(', ')}"
    end
  end
  # rubocop:enable Layout/LineLength

  def error_message
    [options[:message] || :invalid]
  end

  def valid?
    valid_length? && valid_attr?
  end

  def valid_attr?
    valid_regexp?
  end

  def valid_length?
    !value.to_s.strip.empty?
  end

  def valid_regexp?
    value.to_s =~ self.class::REGEXP
  end

end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
lite-validators-1.7.2 lib/lite/validators/base_validator.rb
lite-validators-1.7.1 lib/lite/validators/base_validator.rb
lite-validators-1.7.0 lib/lite/validators/base_validator.rb
lite-validators-1.6.0 lib/lite/validators/base_validator.rb
lite-validators-1.5.0 lib/lite/validators/base_validator.rb
lite-validators-1.4.0 lib/lite/validators/base_validator.rb
lite-validators-1.3.2 lib/lite/validators/base_validator.rb
lite-validators-1.3.1 lib/lite/validators/base_validator.rb
lite-validators-1.3.0 lib/lite/validators/base_validator.rb
lite-validators-1.2.0 lib/lite/validators/base_validator.rb
lite-validators-1.1.2 lib/lite/validators/base_validator.rb
lite-validators-1.1.1 lib/lite/validators/base_validator.rb
lite-validators-1.1.0 lib/lite/validators/base_validator.rb