Sha256: d7f9d8f63e7e40c95c2780f79201be8c9e91bf18f3e5d1c1d3f51a4f99a8d146

Contents?: true

Size: 1.01 KB

Versions: 1

Compression:

Stored size: 1.01 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

  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

  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

1 entries across 1 versions & 1 rubygems

Version Path
lite-validators-1.8.0 lib/lite/validators/base_validator.rb