DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Simpler Tabs

09.19.2008
| 5126 views |
  • submit to reddit
        Just one of many ways to help you add tabs to your layout.

class TabHelper
  attr_reader :html, :tabs

  def initialize(template, states)
    @template = template
    @states = states
    @html = []
    @tabs = {}
  end

  def add(action, text)
    url = { :action => action }
    html = 
      if @template.request.path.sub(/\?.*/, '') == @template.url_for(url)
        @states[:active].call(text, url)
      else
        @states[:inactive].call(text, url)
      end
    @tabs[action] = html
    @html << html
  end
  alias_method :[]=, :add
  
  def [](*args)
    @tabs.values_at(*args)
  end
end

Example:

module ProductsHelper
  def subnav_links
    t = TabHelper.new(self,
      :active   => Proc.new {|text, url| %|<div class="current tab">#{text}</div>| },
      :inactive => Proc.new {|text, url| %|<div class="tab">#{link_to text, url}</div>| }
    )
    t[:index] = 'Manage Products'
    t[:front_page] = 'Manage Front Page'
    
    '<div id="tabs">' +
      '<div style="float: left">' +
        t[:index, :front_page].join +
      '</div>' +
      '<div class="clear"></div>' +
    '</div>'
  end
end