|
| 1 | +# ActiveRecord validator for validating an email address with Blaze Verify |
| 2 | +# |
| 3 | +# Usage: |
| 4 | +# validates :email, presence: true, email: { |
| 5 | +# smtp: true, states: %i[deliverable risky unknown], |
| 6 | +# free: true, role: true, disposable: false, accept_all: true, |
| 7 | +# timeout: 3 |
| 8 | +# } |
| 9 | +# |
| 10 | +# Define an attr_accessor to access verification results. |
| 11 | +# attr_accessor :email_verification_result |
| 12 | +# |
| 13 | +class EmailValidator < ActiveModel::EachValidator |
| 14 | + |
| 15 | + def validate_each(record, attribute, value) |
| 16 | + smtp = boolean_option_or_raise_error(:smtp, true) |
| 17 | + |
| 18 | + states = options.fetch(:states, %i(deliverable risky unknown)) |
| 19 | + allowed_states = %i[deliverable undeliverable risky unknown] |
| 20 | + unless (states - allowed_states).empty? |
| 21 | + raise ArgumentError, ":states must be an array of symbols containing "\ |
| 22 | + "any or all of :#{allowed_states.join(', :')}" |
| 23 | + end |
| 24 | + |
| 25 | + free = boolean_option_or_raise_error(:free, true) |
| 26 | + role = boolean_option_or_raise_error(:role, true) |
| 27 | + disposable = boolean_option_or_raise_error(:disposable, false) |
| 28 | + accept_all = boolean_option_or_raise_error(:accept_all, true) |
| 29 | + |
| 30 | + timeout = options.fetch(:timeout, 3) |
| 31 | + unless timeout.is_a?(Integer) && timeout > 1 |
| 32 | + raise ArgumentError, ":timeout must be an Integer greater than 1" |
| 33 | + end |
| 34 | + |
| 35 | + return if record.errors[attribute].present? |
| 36 | + return unless value.present? |
| 37 | + return unless record.changes[attribute].present? |
| 38 | + |
| 39 | + api_options = { timeout: timeout, smtp: smtp } |
| 40 | + api_options[:accept_all] = true unless accept_all |
| 41 | + ev = BlazeVerify.verify(value, api_options) |
| 42 | + |
| 43 | + result_accessor = "#{attribute}_verification_result" |
| 44 | + if record.respond_to?(result_accessor) |
| 45 | + record.instance_variable_set("@#{result_accessor}", ev) |
| 46 | + end |
| 47 | + |
| 48 | + error ||= ev.state.to_sym unless states.include?(ev.state.to_sym) |
| 49 | + error ||= :free if ev.free? && !free |
| 50 | + error ||= :role if ev.role? && !role |
| 51 | + error ||= :disposable if ev.disposable? && !disposable |
| 52 | + error ||= :accept_all if ev.accept_all? && !accept_all |
| 53 | + |
| 54 | + record.errors.add(attribute, error) if error |
| 55 | + rescue BlazeVerify::Error |
| 56 | + # silence errors |
| 57 | + end |
| 58 | + |
| 59 | + private |
| 60 | + |
| 61 | + def boolean_option_or_raise_error(name, default) |
| 62 | + option = options.fetch(name, default) |
| 63 | + unless [true, false].include?(option) |
| 64 | + raise ArgumentError, ":#{name} must by a Boolean" |
| 65 | + end |
| 66 | + |
| 67 | + option |
| 68 | + end |
| 69 | + |
| 70 | +end |
0 commit comments