Finding The True Domain Using Ruby On Rails
November 3rd, 2008 by ScottK | 2 Comments | Filed in rubySo here’s the problem your Ruby on Rails takes on url and another url. You then need to compare these two inputs to make sure they reside on the same domain. http://techraving.com has the same true domain as https://news.techraving.com. However, http://news.techraving.com does not reside on http://www.yahoo.com. What about http://localhost:8080 as being the same domain as http://localhost:443/index.html.
You could write an overly complication set of methods to start detecting string positions, or even incorporating a bunch of gsub regexs to try and weed out the unwanted components. Or you could take the easy route and call the URI module.
The URI module easily breaks the string url into it’s different parts which you can use to further refine using array’s into what you need for comparison. Taking these two domains:
http://www.techraving.com/about/
http://news.techraving.com/about/
We need to find out whether they are on the same domain. So:
first_domain = URI.parse("http://techraving.com/about/")
second_domain = URI.parse("http://news.techraving.com/about/")
Now first_domain and second_domain are both distinct instances of the URI object. The next step is to let these objects return us the host by calling “host”:
>> first_domain.host => "techraving.com" >> second_domain.host => "news.techraving.com"
That was a lot of work already done for us. But we are not done yet! we still need to find the true domain. Or if you notice that would be the last two index of a possible array. So let’s split into an array:
>> first_array = first_domain.host.split(".")
=> [ "techraving", "com"]
>> second_array = second_domain.host.split(".")
=> ["news", "techraving", "com"]
So the array’s are what we expect in that the last two are the parts we need. Now how best to grab them. Easy enough!
unless first_array.size == 1 first_true_domain = first_array[first_array.size - 2] << "." << first_array[first_array.size - 1] else first_true_domain = first_array[0] end unless second_array.size == 1 second_true_domain = second_array[second_array.size - 2] << "." << second_array[second_array.size - 1] else second_array_true_domain = second_array_array[0] end
Now why can the array size equal 1? That’s because:
>> local_array = URI.parse("http://localhost:80").host.split(".")
=> ["localhost"]
and,
rent a car bulgaria>> local_array = URI.parse("http://localhost:8080").host.split(".") => ["localhost"]
Both are 1 array size and yet the same domain.
So now that we have that out of the way why the index subtraction in the indexes. Because array.size - 2 returns the domain name and array.size - 1 returns the generic top-level domain we can know put the two together by concatenating these two with the “.” to get the true domain.
Now (first_true_domain == second_true_domain) comparisons can be made without sub-domain or port problems. And a ton less string position/replace code.
