Jul 6, 2011 - Ruby on Rails    1 Comment

Dynamically Referencing Named Routes in a Helper

We recently ran into a problem where we needed to create a helper that would create a set of styled links.  It was important that the link for the ‘current’ page be styled differently.  And this helper had to work across multiple controllers.

This seemed easy enough since all of the controllers had a ‘filter’ action that would call a named scope to fetch the appropriate collection of records.  But using named routes made it a bit more difficult.

I’ve over-simplified the approach, partly to contain the code within the limited width of this theme, but also to more fully explain what is going on. Our actual implementation “cleans” things up a bit.

Here is the code:

# In application.rb
# 'key' will be the name of the object `scope`
#  used to fetch the appropriate records
def filter(key)
    ctrl = controller.controller_name
    route = ActionController::Routing::Routes
    url = route.recognize_path(send("filter_#{c}_path".to_sym))
    # Need to overwrite with correct filter
    url.merge!({:filter => key})

    l = link_to key.titleize, url
    if key == params[:filter]
        content_tag(:li, l, :class=>'current')
        content_tag(:li, l)

That’s it.

  • http://www.facebook.com/StinkyHead Chris Habgood

    Cool, man.