Class: ActiveModel::Validations::ColdShoulderValidator

Inherits:
EachValidator
  • Object
show all
Includes:
ActiveSupport::NumberHelper
Defined in:
lib/cold_shoulder.rb

Overview

Extend the rails each validator so that this can be used like any Rails validator

Defined Under Namespace

Modules: HelperMethods

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attr_name, value) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/cold_shoulder.rb', line 25

def validate_each(record, attr_name, value)

  # These are somewhat simplistic
  # Main problem being that all of them can be sidestepped by including commas
  # TODO: Move this outside the validate_each method so we don't define it over and over
  twitter_regex = /(@[A-Za-z0-9_]{1,15})/i
  formatted_phone_regex = /((?:\+?(\d{1,3}))?[- (]*(\d{3})[- )]*(\d{3})[- ]*(\d{4})(?: *x(\d+))?\b)/i
  email_regex = /(\b[^\s]+?\s*(@|at)\s*[^\s]+?\.[^\s]+?\b)/i # Very general so as to catch BS

  # Remove spaces (the most basic way to avoid these detections)
  globbed_value = value.gsub ' ', ''
  bullshit_free_phone = value.gsub /[^0-9,]|\n/i, ''

  # Look for matches
  twitter_handles = globbed_value.scan twitter_regex
  email_addresses = value.scan email_regex
  phone_numbers = globbed_value.scan(formatted_phone_regex).concat(
    bullshit_free_phone.scan(formatted_phone_regex)
  ).uniq

  # Phone numbers
  unless phone_numbers.empty? or options[:ignore_phone]
    record.errors.add(attr_name, :contains_phone_number, options.merge(
      phone_numbers: phone_numbers.map{ |p| 
        defined?(Rails) ? number_to_phone(p[0]) : p[0]
      }.join(', ')
    ))
  end

  # Email addys
  unless email_addresses.empty? or options[:ignore_email]
    record.errors.add(attr_name, :contains_email_address, options.merge(
      email_addresses: email_addresses.map{|p| p[0] }.join(', ')
    ))
  else

    # Twitter handles
    # Any email address is going to register twitter handles as well
    unless twitter_handles.empty? or options[:ignore_twitter]
      record.errors.add(attr_name, :contains_twitter_handle, options.merge(
        handles: twitter_handles.map{|p| p[0] }.join(', ')
      ))
    end

  end
end