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:
- def active?(*routes)
- is_active = false
- routes.each do |route|
- c, a = route.match(/\#/) ? route.split('#') : [route, nil]
- c = c.camelize
- is_active = if a
- controller.class.to_s =~ /#{c}/ && action_name == a
- else
- controller.class.to_s =~ /#{c}/
- end
- end
- is_active
- end
To see if a particular route is active, just pass in it as an argument (or as multiple arguments) in Rails routes syntax:
- # returns true when on the 'show' action of ArticlesController
- active?('articles#show')
- # returns true when on the 'show' action of Content::ArticlesController
- active?('content/articles#show')
- # returns true when on ANY action of ArticlesController
- active?('articles')
- # returns true when on ANY action of ANY controller within the Content:: namespace
- active?('content/')
- # returns true when on EITHER the 'show' or 'index' actions of ArticlesController
- active?('articles#show', 'articles#index')
- def active?(*routes)
- routes.any? do |route|
- c, a = route.match(/\#/) ? route.split('#') : [route, nil]
- controller.class.to_s == "#{c.camelize}Controller" && (a ? action_name == a : true)
- end
- end
Posted Nov 9th, 2011. Tagged ruby, rails
blog comments powered by Disqus
© 2011 rawnet.com