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
Is this the sort of thing you're after?
def same_url?(one, two)
url_for(one) == url_for(two)
end
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With