Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 7th, 2012  |  syntax: None  |  size: 0.96 KB  |  hits: 6  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. In Rails, how do I determine if two URLs are equal?
  2. def is_same_controller_and_action?(url1, url2)
  3.   hash_url1 = Rails.application.routes.recognize_path(url1)
  4.   hash_url2 = Rails.application.routes.recognize_path(url2)
  5.  
  6.   [:controller, :action].each do |key|
  7.     return false if hash_url1[key] != hash_url2[key]
  8.   end
  9.  
  10.   return true
  11. end
  12.        
  13. def to_canonical(url)
  14.   uri = Addressable::URI.parse(url)
  15.   uri.scheme = "http" if uri.scheme.blank?
  16.   host = uri.host.sub(/www./, '') if uri.host.present?
  17.   path = (uri.path.present? && uri.host.blank?) ? uri.path.sub(/www./, '') : uri.path
  18.   uri.scheme.to_s + "://" + host.to_s + path.to_s
  19. rescue Addressable::URI::InvalidURIError
  20.   nil
  21. rescue URI::Error
  22.   nil
  23. end
  24.        
  25. > to_canonical('www.example.com') => 'http://example.com'
  26. > to_canonical('http://example.com') => 'http://example.com'
  27.        
  28. uri = Addressable::URI.parse("http://www.詹姆斯.com/")
  29. uri.normalize
  30. #=> #<Addressable::URI:0xc9a4c8 URI:http://www.xn--8ws00zhy3a.com/>