Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way in Rails to determine if two (or more) given URLs (as strings or hash options) are equal?

I'm wanting a method called same_url? that will return true if the passed in URLs are equal. The passed in URLs might be either params options hash or strings.

same_url?({:controller => :foo, :action => :bar}, "http://www.example.com/foo/bar") # => true

The Rails Framework helper current_page? seems like a good starting point but I'd like to pass in an arbitrary number of URLs.

As an added bonus It would be good if a hash of params to exclude from the comparison could be passed in. So a method call might look like:

same_url?(projects_path(:page => 2), "projects?page=3", :excluding => :page) # => true 
like image 624
nutcracker Avatar asked Sep 24 '08 10:09

nutcracker


2 Answers

Is this the sort of thing you're after?

def same_url?(one, two)
  url_for(one) == url_for(two)
end
like image 28
Codebeef Avatar answered Nov 01 '22 22:11

Codebeef


Here's the method (bung it in /lib and require it in environment.rb):

def same_page?(a, b, params_to_exclude = {})
  if a.respond_to?(:except) && b.respond_to?(:except)
    url_for(a.except(params_to_exclude)) == url_for(b.except(params_to_exclude))
  else
    url_for(a) == url_for(b)
  end
end

If you are on Rails pre-2.0.1, you also need to add the except helper method to Hash:

class Hash
  # Usage { :a => 1, :b => 2, :c => 3}.except(:a) -> { :b => 2, :c => 3}
  def except(*keys)
    self.reject { |k,v|
      keys.include? k.to_sym
    }
  end
end

Later version of Rails (well, ActiveSupport) include except already (credit: Brian Guthrie)

like image 71
Dave Nolan Avatar answered Nov 01 '22 22:11

Dave Nolan