Rear end rails
How can I check a text column that it does not contain websites, examples would be:
www.google.com
google.com
http://gooogle.com
http://www.google.com
https://www.google.com
https://google.com
I want to do this on the front side, but on the back end. I'm more interested in the rear end at the moment as I will be dealing with the front end later
Update question:
With the example provided by Mr. Yoshiji, I came up with a case that is not covered:
http://rubular.com/r/VGgWyfIt7R
See http://www.google.com
in the middle of the text? and it doesn't match? This is exactly what I need to make it fit. So I can throw a validation error saying you cannot host websites.
a source to share
I found a strong regexp, credits go to @PhillPafford ( PHP RegEx for "Site Name"). If you confirm your answer, please unpin it first!):
/^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/
To see it in action:
http://rubular.com/r/GOHHrucCdX
UPDATE:
This text will find names anywhere in the text:
/(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?/
Note that I removed ^
the beginning and $
end to make it work inside the text:
Rubular source:
^ Start of line
$ End of line
http://rubular.com/r/iEVzfv2U3O
@GandalfStormCrow noticed the following:
Since I was little.My first dog
#^^^
The only way to solve this problem is to replace little.My
with little. My
:
text.gsub(/\w\.[A-Z]/) { |matched_string| matched_string.gsub('.', '. ') }
See it in action:
1.9.3p489 :018 > text = "hello my name is robert.My dog"
=> "hello my name is robert.My dog"
1.9.3p489 :019 > text.gsub(/\w\.[A-Z]/) { |matched_string| matched_string.gsub('.', '. ') }
=> "hello my name is robert. My dog"
a source to share
I see many have used the regex approach, but perhaps you need to create a simple blacklist. Sort of:
class MyModel < ActiveRecord::Base
BLACKLIST = [
'google.com'
]
validate :disallow_blacklisted_urls
private
def disallow_blacklisted_urls
BLACKLIST.each do |blacklisted_url|
if my_field && my_field.include?(blacklisted_url)
errors.add(:my_field, "must not contain #{blacklisted_url}")
end
end
end
end
The reason I will go this way is that you can easily add more urls (facebook.com, twitter.com) and it will still work and will be clear after a year from not seeing the code, in while the regex is too cryptic for my aging eyes (and brain :-)). Also, if you don't want to check the whole blacklist every time, you can add a break to the main condition of the check method, but I think the user will have better reviews like this.
a source to share