Пламен обнови решението на 28.11.2012 07:55 (преди почти 12 години)
+module Validations
+ def self.email?(value)
+ email_parts = value.match /\A[A-Za-z0-9][-A-Za-z0-9_+\.]{,200}@(?<host>.+)\z/
+ return false if !email_parts
+
+ hostname? email_parts[:host]
+ end
+
+ def self.phone?(value)
+ !!(value =~ /\A(0|(\+|00)[1-9]\d{,2})([- ()]{,2}\d){6,11}\z/)
+ end
+
+ def self.hostname?(value)
+ !!(value =~ /\A(([A-Za-z0-9]{1,2}|[A-Za-z0-9][-A-Za-z0-9]{,60}[A-Za-z0-9])\.)+[A-Za-z]{2,3}\z/)
+ end
+
+ def self.ip_address?(value)
+ octets = value.split '.'
+
+ octets.size == 4 && octets.all? { |octet| integer?(octet) && (0..255).include?(octet.to_i) }
+ end
+
+ def self.number?(value)
+ !!(value =~ /\A-?(0|[1-9]\d*)(\.\d+)?\z/)
+ end
+
+ def self.integer?(value)
+ !!(value =~ /\A-?(0|[1-9]\d*)\z/)
+ end
+
+ def self.date?(value)
+ return false if !(value =~ /\A\d\d\d\d-(\d\d)-(\d\d)\z/)
+
+ (1..12).include?($1.to_i) && (1..31).include?($2.to_i)
+ end
+
+ def self.time?(value)
+ return false if !(value =~ /\A(\d\d):(\d\d):(\d\d)\z/)
+
+ (0..23).include?($1.to_i) && (0..59).include?($2.to_i) && (0..59).include?($3.to_i)
+ end
+
+ def self.date_time?(value)
+ date_parts = value.match /\A(?<date>[-\d]+)[\s|T](?<time>[:\d]+)\z/
+ return false if !date_parts
+
+ date?(date_parts[:date]) && time?(date_parts[:time])
+ end
+end
+
+class PrivacyFilter
+ attr_accessor :preserve_phone_country_code, :preserve_email_hostname, :partially_preserve_email_username
+
+ def initialize(text)
+ @text = text
+ end
+
+ def filtered
+ filtered = @text.gsub(/\b\S+@\S+\b/) { |match| Validations.email?(match) ? filter_email(match) : match }
+ filtered.gsub!(/(0|\+)[- ()\d]+/) { |match| Validations.phone?(match) ? filter_phone(match) : match }
+
+ filtered
+ end
+
+ private
+
+ def filter_email(email)
+ return email.sub(/[^@]+/) { |username| obfuscure_username username } if @partially_preserve_email_username
+ return email.sub(/[^@]+/, '[FILTERED]') if @preserve_email_hostname
+
+ '[EMAIL]'
+ end
+
+ def obfuscure_username(username)
+ if username.length > 6
+ username[0, 3] + '[FILTERED]'
+ else
+ '[FILTERED]'
+ end
+ end
+
+ def filter_phone(phone)
+ if @preserve_phone_country_code && phone_international?(phone)
+ phone[/\A(00|\+)\d{3}/] + ' [FILTERED]'
+ else
+ '[PHONE]'
+ end
+ end
+
+ def phone_international?(phone)
+ !!(phone =~ /\A\+|00/)
+ end
+end