2012-08-01 59 views
1

如果我在Rails中有兩個URL(無論它們是字符串形式還是URI對象),確定它們是否相等的最好方法是什麼?這似乎是一個相當簡單的問題,但即使其中一個URL是相對的,另一個是絕對的,或者其中一個URL的參數不同於其他參數,我也需要解決方案。在Rails中,我如何確定兩個URL是否相等?

我已經看過What is the best way in Rails to determine if two (or more) given URLs (as strings or hash options) are equal?(和其他幾個問題),但問題很老,建議的解決方案無法按照我需要的方式工作。

+0

那麼,什麼是你想要的方式?它何時應該返回真實?只需檢查控制器和操作? – 2012-08-01 13:56:06

+0

@AnthonyAlberto我想我的原始問題是要求一個更通用的解決方案,它將採用任何兩個URL(即使它們指的是外部站點上的頁面),並檢查它們是否引用同一頁面。想想看,雖然只是檢查控制器和行動實際上對我來說很好。 – Ajedi32 2012-08-01 14:36:05

+0

但它是在你的應用程序的上下文嗎?或者你需要測試任何網址? – 2012-08-01 14:40:44

回答

4

只要你有URL1和URL2是含有URL一些字符串:

def is_same_controller_and_action?(url1, url2) 
    hash_url1 = Rails.application.routes.recognize_path(url1) 
    hash_url2 = Rails.application.routes.recognize_path(url2) 

    [:controller, :action].each do |key| 
    return false if hash_url1[key] != hash_url2[key] 
    end 

    return true 
end 
+0

太好了,那正是我需要的!謝謝你的幫助。 – Ajedi32 2012-08-01 15:04:47

0

結帳的addressable寶石並且具體地normalize方法(及其documentation)和heuristic_parse方法(及其documentation)。我過去使用過它,發現它非常強大。

尋址即使處理Unicode字符的URL在其中:

uri = Addressable::URI.parse("http://www.詹姆斯.com/") 
uri.normalize 
#=> #<Addressable::URI:0xc9a4c8 URI:http://www.xn--8ws00zhy3a.com/> 
3

1)轉換網址canonical form

在我目前的項目我使用addressable寶石爲了做到這一點:

def to_canonical(url) 
    uri = Addressable::URI.parse(url) 
    uri.scheme = "http" if uri.scheme.blank? 
    host = uri.host.sub(/\www\./, '') if uri.host.present? 
    path = (uri.path.present? && uri.host.blank?) ? uri.path.sub(/\www\./, '') : uri.path 
    uri.scheme.to_s + "://" + host.to_s + path.to_s 
rescue Addressable::URI::InvalidURIError 
    nil 
rescue URI::Error 
    nil 
end 

例如:

> to_canonical('www.example.com') => 'http://example.com' 
> to_canonical('http://example.com') => 'http://example.com' 

2)比較你的網址:canonical_url1 == canonical_url2

UPD:

  • Does it work with sub-domains? - 不,我的意思是,我們不能說translate.google.comgoogle.com是相等的。當然,你可以根據你的需要修改它。
+0

這將工作與子域?如何使用[addressabler](https://github.com/flipsasser/addressabler)gem來檢查子域是否存在,如果不是,則將其強制爲* www * * – stephenmurdoch 2012-08-01 14:59:06

+0

這看起來很棒,但是您提供的方法不會與相關網址一起工作:'to_canonical('/ test')=>「http:/// test」' 可尋址的gem看起來與我在這裏要做的事情非常相關。 – Ajedi32 2012-08-01 15:09:43

+0

@stephenmurdoch我已經更新了我的答案。至於尋址寶石,它似乎並不是非常積極的維護。 – melekes 2012-08-01 15:10:29

相關問題