= StatefulLink
StatefulLink is a helper that simplifies displaying stateful navigation links. State
depends on current controller and action.
= Installation
Rails3 only Add the following line to your Gemfile:
gem 'stateful_link'
= Tutorial
Let we have RESTful PostsController and two navigation links in layout.
layouts/application.html.erb
-
<%= link_to "Posts", posts_url %>
- <%= link_to "New post", new_post_url %>
So, at every page we have same links. But in good form we should mark
current user location by changing visual appearance of current and parent navigation
links. For example, if user opens new post page, "New post" should be displayed
as regular text, and "Posts" should become bold.
Solution:
posts_controller.rb
class PostsController < ApplicationController
end
application_helper.rb
module ApplicationHelper
def navigation_link(label, active, chosen, url)
stateful_link_to(
active,
chosen,
:active => proc { label },
:chosen => proc { content_tag :b, link_to(label, url) },
:inactive => proc { link_to label, url }
)
end
end
layouts/application.html.erb
<ul>
<li>
<%= navigation_link("Posts", "posts#index", "posts#*", posts_url) %>
<ul>
<%= navigation_link("New post", ["posts#new", "posts#create"], nil, new_post_url) %>
</ul>
</li>
</ul>
= Examples
posts/index.html.erb
<%= "we are in PostsController::index" if action_any_of?("posts#index") %>
<%= "we are in PostsController::index" if action_any_of?("#index") %>
<%= "action state is active" if action_state("#index") == :active %>
<%= "action state is chosen" if action_state("#show", ["#index", "#edit", "#update"]) == :chosen %>
<%= "action state is inactive" if action_state("users#index") == :inactive %>