Skip to content

gzigzigzeo/stateful_link

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

34 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

StatefulLink

StatefulLink is a helper that simplifies displaying stateful navigation links.

Installation

Rails 3 only. Add the following line to your Gemfile:

gem 'stateful_link'

Problem

Let we have RESTful PostsController and two navigation links in layout.

layouts/application.html.erb
  <ul>
    <li>
      <%= link_to "Posts", posts_url %>
      <ul>
        <li><%= link_to "New post", new_post_url %></li>
      </ul>
    </li>
  </ul>

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 => proc { label },
        :chosen => proc { content_tag :b, link_to(label, url) },
        :inactive => proc { link_to label, url },
        :state => proc {
          if action_any_of?(active) # See below
            :active
          elsif action_any_of?(chosen)
            :chosen
          else
            :inactive
          end
        }
      )
    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 %>

About

StatefulLink is a helper that simplifies displaying stateful navigation links

Resources

License

Stars

Watchers

Forks

Packages

No packages published