Никола обнови решението на 27.11.2012 23:33 (преди почти 12 години)
+module ValidationExpressions
+ PHONE = '((?<=[^a-zA-Z0-9\+]|\A)0|(?<prefix>(00|\+)[1-9]\d{,2}))([ \(\)-]{,2}\d){6,11}'
+ IP_ADDRESS = '((\d{1,2}|(1\d{2}|2([0-4]\d|5[0-5])))\.){3}\g<2>'
+ INTEGER = '-?(0|[1-9]\d*)'
+ NUMBER = INTEGER + '(\.\d+)?'
+ DATE = '\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])'
+ TIME = '([01]\d|2[0-3])\:(?<sec>[0-5]\d)\:\g<sec>'
+ DATE_TIME = "#{DATE}[ T]#{TIME}"
+ HOSTNAME = '((?<let>[a-zA-Z0-9])((\g<let>|-){,61}\g<let>)?\.)+[a-zA-Z]{2,3}(\.[a-zA-Z]{2})?'
+ EMAIL_USERNAME = '(\b((?<partial>(?<n>[a-zA-Z0-9])(?<nws>[\w\+\.-]){2})\g<nws>{3,198}|\g<n>\g<nws>{,4}))'
+ FULL_EMAIL = "#{EMAIL_USERNAME}@#{HOSTNAME}"
+end
+
+class PrivacyFilter
+ include ValidationExpressions
+
+ attr_accessor :preserve_phone_country_code
+ attr_accessor :preserve_email_hostname
+ attr_accessor :partially_preserve_email_username
+
+ def initialize(text)
+ @text = text
+ end
+
+ def filtered
+ filter_phone filter_email @text
+ end
+
+ private
+
+ def filter_phone(text)
+ text.gsub /#{PHONE}/ do
+ if preserve_phone_country_code && !$~['prefix'].nil?
+ "#{$~['prefix']} [FILTERED]"
+ else
+ '[PHONE]'
+ end
+ end
+ end
+
+ def filter_email(text)
+ text.gsub /#{email_expression}/, email_filtered_message
+ end
+
+ def email_expression
+ if @partially_preserve_email_username or @preserve_email_hostname
+ "#{EMAIL_USERNAME}(?=@#{HOSTNAME})"
+ else
+ FULL_EMAIL
+ end
+ end
+
+ def email_filtered_message
+ if @partially_preserve_email_username then '\k<partial>[FILTERED]'
+ elsif @preserve_email_hostname then '[FILTERED]'
+ else '[EMAIL]'
+ end
+ end
+end
+
+
+class Validations
+ include ValidationExpressions
+
+ def self.phone?(value)
+ self.match_expression PHONE, value
+ end
+
+ def self.ip_address?(value)
+ self.match_expression IP_ADDRESS, value
+ end
+
+ def self.number?(value)
+ self.match_expression NUMBER, value
+ end
+
+ def self.integer?(value)
+ self.match_expression INTEGER, value
+ end
+
+ def self.date?(value)
+ self.match_expression DATE, value
+ end
+
+ def self.time?(value)
+ self.match_expression TIME, value
+ end
+
+ def self.date_time?(value)
+ self.match_expression DATE_TIME, value
+ end
+
+ def self.email?(value)
+ self.match_expression FULL_EMAIL, value
+ end
+
+ def self.hostname?(value)
+ self.match_expression HOSTNAME, value
+ end
+
+ protected
+
+ def self.match_expression(expression, value)
+ not /\A#{expression}\z/.match(value).nil?
+ end
+end