Sha256: 1b6f5da9b6f6362c679c7a4765ff58c111ed56d0ef9fb7ea063fb36145018479

Contents?: true

Size: 1.92 KB

Versions: 5

Compression:

Stored size: 1.92 KB

Contents

= 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
    <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, 
          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 %>

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
stateful_link-0.0.9 README.rdoc
stateful_link-0.0.8 README.rdoc
stateful_link-0.0.7 README.rdoc
stateful_link-0.0.6 README.rdoc
stateful_link-0.0.5 README.rdoc