link_to_remote_unless_current

07 Jun 2006

Here’s my wishlist for right now: link_to_remote_unless_current

I’m developing a page with some pieces of navigation that reload the content in the center of the page. The navigation should be unlinked when it’s active - so it’s a perfect example of when link_to_unless_current would be used - except I want it AJAXified. Yes, yes I just used that word. I happen to like that word.

So I browsed through the ActionView helpers and saw that they fit together reall well, and that there was a big gap where something like link\_to\_remote\_unless\_current (or remote\_link\_to\_unless\_current depending on your preference) was needed.

After trying to piece things together the difficult way I realized that I had, like so many of us Ruby noobs often do, completely overcomplicated it. Here’s the final code:

~~~~ruby def link_to_remote_unless_current(name, options = {}, html_options = {}) current_page?(options[:url]) ? name : link_to_function(name, remote_function(options), html_options) end ~~~~

To use this, just added it in your ApplicationHelper module (found in ./app/helpers/application_helper.rb).

If you wanted the longer (and slightly more rails-like) version that calls a block and which, frankly, I just don’t understand:

~~~~ruby def link_to_remote_unless_current(name, options = {}, html_options = {}, *parameters_for_method_reference, &block) if current_page?(options[:url]) if block_given? block.arity <= 1 ? yield(name) : yield(name, remote_function(options), html_options, *parameters_for_method_reference) else name end else link_to_function(name, remote_function(options), html_options) end end ~~~~

Let me know if this helps you out!

  • Tom said: Post it as a patch!
  • Danger said: Hey, not a bad idea. I'll fix it up a bit and I think I'll do just that.
  • Adam said: Hey Danger - I've tried out both methods and neither seem to be working out for me... maybe there's something I'm missing? Could you give an example of how to call the method correctly, or maybe email me? Thanks for any help! I'm in desperate need of a link_to_remote_unless_current!
  • Adam said: Hey Danger - I've tried out both methods and neither seem to be working out for me... maybe there's something I'm missing? Could you give an example of how to call the method correctly, or maybe email me? Thanks for any help! I'm in desperate need of a link_to_remote_unless_current!
  • Adam said: Ah, I'm SO sorry!

Please if you found this post helpful or have questions.