Since http:// contains so many forward slashes, this would be a good use for Ruby's %r{} regex literal syntax.
def has_forbidden_prefix?(string)
string =~ %r{^(http://|www)}
end
This will return nil, falsy, if the string does not start with http:// or www.
It will return 0, truthy (the offset of the first match) if the string does.
You can use validate :some_method_name to call a custom validation method in the model, I would structure it as follows
model MyThing
validate :no_forbidden_prefix
private
def has_forbidden_prefix?(string)
string =~ %r{^(http://|www)}
end
def no_forbidden_prefix
if has_forbidden_prefix?(uri)
errors.add :domain, 'The URI cannot start with "http://" or "www"'
end
end
end