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}"
      parameters = request.parameters

      excluding.each do |key|

      request_string = CGI.escapeHTML(url_for(parameters))
      url_string == request_string

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

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.

This entry was posted in programming and tagged , . Bookmark the permalink.

2 Responses to current_page?

Leave a Reply

Your email address will not be published. Required fields are marked *