Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- module UnsortedList
- def sort_ul(list)
- html = ""
- while list.size > 0
- row = list.shift
- link = get_link(row[:link])
- if list.size > 0
- if row[:nivel] == list[0][:nivel] #estamos en el mismo nivel?
- html << "<li>#{link}</li>"
- elsif row[:nivel] < list[0][:nivel] #estamos en un nivel superior?
- html << "<li>#{link}<ul>" + sort_ul(list) + "</ul></li>"
- else
- end
- else
- html << "<li>#{link}</li>"
- end
- end
- if row[:nivel] == 1
- "<ul>" + html + "</ul>"
- else
- html
- end
- end
- def sort_ul2(list)
- current_level = 0
- html = ""
- list.each do |item|
- level, link = item[:nivel], item[:link]
- link = get_link(link)
- if level > current_level
- html<< "<ul><li>"
- html<< "#{link}"
- elsif level == current_level
- html<< "</li><li>#{link}"
- else
- (current_level - level).times { html<< "</li></ul>" }
- html<< "</li><li>#{link}"
- end
- current_level = level
- end
- # Close ULs left open
- current_level.times.each do
- html<< "</li></ul>"
- end
- html
- end
- def get_link(link)
- "<a href='##{link.downcase}'>#{link}</a>"
- end
- end
- require 'test/unit'
- class TestNestedList < Test::Unit::TestCase
- include UnsortedList
- def setup
- @simple = [{:nivel => 1, :link => "1"},{:nivel => 1, :link => "2"}]
- @simple_r = "<ul><li><a href='#1'>1</a></li><li><a href='#2'>2</a></li></ul>"
- @complex = [{:nivel => 1, :link => "1"},{:nivel => 2, :link => "1.1"},{:nivel => 3, :link => "1.1.1"}]
- @complex_r = "<ul><li><a href='#1'>1</a><ul><li><a href='#1.1'>1.1</a><ul><li><a href='#1.1.1'>1.1.1</a></li></ul></li></ul></li></ul>"
- @more_complex = [{:nivel => 1, :link => "1"},{:nivel => 2, :link => "1.1"},{:nivel => 2, :link => "1.2"},{:nivel => 3, :link => "1.2.1"},{:nivel => 3, :link => "1.2.2"},{:nivel => 1, :link => "2"}]
- @more_complex_r = "<ul><li><a href='#1'>1</a><ul><li><a href='#1.1'>1.1</a></li><li><a href='#1.2'>1.2</a><ul><li><a href='#1.2.1'>1.2.1</a></li><li><a href='#1.2.2'>1.2.2</a></li></ul></li></ul></li><li><a href='#2'>2</a></li></ul>"
- end
- # prueba con sort_ul
- def test_it_should_return_simple_list
- assert_equal @simple_r, sort_ul(@simple)
- end
- def test_it_should_return_nested_list
- assert @complex_r, sort_ul(@complex)
- end
- def test_it_should_return_complex_nested_list
- assert @more_complex_r, sort_ul(@more_complex)
- end
- # prueba con sort_ul2
- def test_it_should_return_simple_list2
- assert_equal @simple_r, sort_ul2(@simple)
- end
- def test_it_should_return_nested_list2
- assert @complex_r, sort_ul2(@complex)
- end
- def test_it_should_return_complex_nested_list2
- assert @more_complex_r, sort_ul2(@more_complex)
- end
- end
Add Comment
Please, Sign In to add comment