Sha256: ae604768af39f9b2febf53c7c9b132b09b9e770f978e40ded38f55bb2f308759

Contents?: true

Size: 709 Bytes

Versions: 1

Compression:

Stored size: 709 Bytes

Contents

require "active_model"
require "email_parser"

class EmailValidator < ActiveModel::EachValidator
  class << self
    attr_accessor :default_parser_options
  end

  self.default_parser_options = {}

  def initialize(*_args)
    super
    parser_options = options.each_with_object({}) do |(k, v), h|
      h[k] = v if EmailParser::OPTIONS.include?(k)
    end
    @parser = EmailParser.new(**self.class.default_parser_options.merge(parser_options))
  end

  def validate_each(record, attribute, value)
    if value.nil?
      return if options[:allow_nil]

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

    return if @parser.valid?(value)

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

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
email_parser-0.1.2 lib/email_parser/validator.rb