This weekend I found myself caught in a love/hate relationship with a certain method in rails. I love this method because it uses some sort of mind control to know exactly when to show a link and when to show text. This method I speak of is UrlHelper.link_to_unless_current. My beef is not with this method directly, but the underlying UrlHelper.current_page?.
What dissapponted me about this method was the inability to exclude certain parameters from the check. The reason why this is important is because I may not want the “page” variable to be considered when verifying if the current url is the one in the link_to statement. So I ended up adding an overriding the current_page? method and this is what I ended up with:
def current_page?(options, excluding = {})
url_string = CGI.escapeHTML(url_for(options))
request = @controller.request
if url_string =~ /^\w+:\/\//
url_string == "#{request.protocol}#{request.host_with_port}#{request.request_uri}"
else
parameters = request.parameters
excluding.each do |key|
parameters.delete(key)
end
request_string = CGI.escapeHTML(url_for(parameters))
url_string == request_string
end
end
I basically copied and pasted the current_page? code from the rails repository. With a few modifications. First I grabbed the collection of request.parameters and removed any items that are in the excluding list. Then I rebuilt the url using the url_for method.
With this modification it made it very easy to make link_to_unless_current_with_paging:
def link_to_unless_current_with_paging(name, options = {}, html_options = {}, *parameters_for_method_reference, &block)
link_to_unless current_page?(options, ['page']), name, options, html_options, *parameters_for_method_reference, &block
end
Hope this helps someone else out there that is getting frustrated with link_to_unless_current. What would be really nice is if this worked its way into the repository. Maybe I will get the nerve to make a patch, and be rejected.
Tags: rails, ruby
2 responses so far ↓
1 N Y // Aug 15, 2008 at 12:51 am
Hey great post. Thanks for sharing your code.
I thought you might be interested in a second way that this can be solved. You can do something like pass in the params into the original current_page? function and avoid implementing your own.
here is an example:
current_page?(:action => 'global', :page => params[:page])
2 Cameron // Sep 9, 2008 at 5:59 pm
Just what I was struggling with!! Genuis
Leave a Comment