3

I have the following ruby code in a model:

if privacy_policy_link.match(/#{domain}($|\/$)/) errors.add(:privacy_policy_link, 'Link to a specific privacy policy page on your site instead of your homepage.') end

This worked until a user tried to save a privacy policy link that looked like this:

https://example.com/about-me/privacy-policy-for-example-com/

The goal is that I don't want them linking to their base homepage (example.com or www.example.com etc) for this privacy policy link (for some random, complicated reasons I won't go into). The link provided above should pass the matcher (meaning that because they are linking to a separate page on their site, it shouldn't be considered a match and they shouldn't see any errors when saving the form) - but because they reference their base domain in second half of the url, it comes up as a match.

I cannot, for the life of me, figure out how the correct regex on rubular to get this url to pass the matching algorithm. And of course I cannot just ask the user to rename their privacy policy link to remove the "com" from it at the end - because this: https://example.com/about-me/privacy-policy-for-example would pass. :)

I would be incredibly grateful for any assistance that could help me understand how to solve this problem!

Rubular link: http://rubular.com/r/G5OmYfzi6t

pixelcandy
  • 109
  • 6

1 Answers1

2

Your issue is the . character is any character so it matched the - in example-com.

If you chain it to the beginning of the line it will match correctly without trying to escape the . in the domain.

if privacy_policy_link.match(%r{^(http[s]?://|)(www.)?#{domain}($|/$)})
Nick Ellis
  • 1,048
  • 11
  • 24
  • ahh ok that makes total sense! Thank you for explaining that and for providing a working solution. I really appreciate that! – pixelcandy Dec 18 '18 at 19:53
  • 1
    Little suggestion - to make your regular expression a bit more readable you can use `%r{}` like so: `%r{^(http[s]?://|)(www.)?#{domain}($|/$)}` – John Gallagher Dec 18 '18 at 20:16