Sha256: 13c7f5928ddca034c7b64fe69d9cbc803aaf6bcc9d60d211f499b253d70c9929

Contents?: true

Size: 685 Bytes

Versions: 2

Compression:

Stored size: 685 Bytes

Contents

require "active_model"
require "email_parser"

class EmailValidator < ActiveModel::EachValidator
  attr_reader :allow_nil

  class << self
    attr_accessor :default_parser_options
  end

  self.default_parser_options = {}

  def initialize(*_args)
    super
    parser_options = options.dup
    @allow_nil = parser_options.delete(:allow_nil)
    @parser = EmailParser.new(**self.class.default_parser_options.merge(parser_options))
  end

  def validate_each(record, attribute, value)
    if value.nil?
      return if allow_nil

      record.errors.add(attribute, :blank)
      return
    end

    return if @parser.valid?(value)

    record.errors.add(attribute, :invalid)
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
email_parser-0.1.1 lib/email_parser/validator.rb
email_parser-0.1.0 lib/email_parser/validator.rb