Active routes in Rails

Mike
@mikerfulcher on Twitter
6twenty on GitHub

Not long ago I needed to put together a little helper to determine if a particular route (eg /content) was active, in order to identify which menu items should be in an 'active' state. It needed to be flexible enough to match a broad range of routes: some menu items remain active no matter where you are in a particular namespace, whereas others were active only on a particular action in a particular controller. Moreover, some menu items were active when you were in one of a collection of specific actions.

I thought, what better example to base this on that Rails' own routes syntax?

Here's the result:

  1. def active?(*routes)
  2. is_active = false
  3. routes.each do |route|
  4. c, a = route.match(/\#/) ? route.split('#') : [route, nil]
  5. c = c.camelize
  6. is_active = if a
  7. controller.class.to_s =~ /#{c}/ && action_name == a
  8. else
  9. controller.class.to_s =~ /#{c}/
  10. end
  11. end
  12. is_active
  13. end

To see if a particular route is active, just pass in it as an argument (or as multiple arguments) in Rails routes syntax:

  1. # returns true when on the 'show' action of ArticlesController
  2. active?('articles#show')
  3. # returns true when on the 'show' action of Content::ArticlesController
  4. active?('content/articles#show')
  5. # returns true when on ANY action of ArticlesController
  6. active?('articles')
  7. # returns true when on ANY action of ANY controller within the Content:: namespace
  8. active?('content/')
  9. # returns true when on EITHER the 'show' or 'index' actions of ArticlesController
  10. active?('articles#show', 'articles#index')


Update December 14th, 2011: a more concise version:

  1. def active?(*routes)
  2. routes.any? do |route|
  3. c, a = route.match(/\#/) ? route.split('#') : [route, nil]
  4. controller.class.to_s == "#{c.camelize}Controller" && (a ? action_name == a : true)
  5. end
  6. end

Posted Nov 9th, 2011. Tagged ruby, rails


blog comments powered by Disqus



© 2011 rawnet.com