Skip to content

Commit

Permalink
Add nesting
Browse files Browse the repository at this point in the history
  • Loading branch information
Daniel Haran committed Oct 26, 2008
1 parent a4d85c1 commit 6f41f6d
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 9 deletions.
4 changes: 3 additions & 1 deletion README
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
= SemanticMenu

A plugin to make menus easier to write. Does not support nesting yet
A plugin to make large menus easier to write.

Supports arbitrarily deep nesting; parents will be marked as 'active' if any of its children are active.

== Example

Expand Down
2 changes: 1 addition & 1 deletion TODO
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
-add nesting
-add css + task for copying it over
-add procs to active?
21 changes: 14 additions & 7 deletions lib/semantic_menu.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,25 @@ class MenuItem
include ActionView::Helpers::TagHelper,
ActionView::Helpers::UrlHelper

attr_accessor :children

def initialize(title, link)
@title, @link = title, link
@title, @link, @children = title, link, []
end

def add(title, link, &block)
adding = MenuItem.new(title, link)
@children << adding
yield adding if block_given?
end

def to_s
opts = active? ? {:class => 'active'} : {}
content_tag :li, link_to(@title, @link), opts
content_tag :li, link_to(@title, @link) + child_output, opts
end

def child_output
children.empty? ? '' : content_tag(:ul, @children.collect(&:to_s).join)
end

def active?
Expand All @@ -27,7 +39,6 @@ def controller # make it available to current_page? in UrlHelper

class SemanticMenu < MenuItem

attr_accessor :children
def initialize(controller, opts={},&block)
@@controller = controller

Expand All @@ -39,10 +50,6 @@ def initialize(controller, opts={},&block)
def to_s
content_tag(:ul, @children.collect(&:to_s).join, @opts)
end

def add(title, link)
@children << MenuItem.new(title, link)
end
end

# Yep, monkey patch ActionView's UrlHelper
Expand Down
19 changes: 19 additions & 0 deletions test/semantic_menu_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,25 @@ def test_menu_item_shows_active_if_on_current_page
assert_equal '<li class="active"><a href="link">title</a></li>', item.to_s
end

def test_nested_menu
MenuItem.any_instance.stubs(:active?).returns(true)
menu = SemanticMenu.new(nil) do |root|
root.add 'level1', 'link_level1' do |link1|
link1.add 'level2', 'link_level2'
end
end
expected = <<NESTED
<ul class="menu">
<li class="active"><a href="link_level1">level1</a>
<ul>
<li class="active"><a href="link_level2">level2</a></li>
</ul>
</li>
</ul>
NESTED
assert_equal expected.gsub(/\n */, '').gsub(/\n/, ''), menu.to_s
end

protected
def default_menu
SemanticMenu.new nil, :class => 'mymenu' do |root|
Expand Down

0 comments on commit 6f41f6d

Please sign in to comment.