Created
October 12, 2010 16:04
-
-
Save xenda/622430 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module UnsortedList | |
| def sort_ul(list, level = 0) | |
| html = "<ul>" | |
| list.map do |row| | |
| if row[:nivel] =~ /(.*)\..{#{level+1}}/ | |
| captured = $1 | |
| sequence = list.select {|row| row[:nivel] =~ /^#{captured}\..*$/ } | |
| list -= sequence | |
| html << sort_ul(sequence,level+1) | |
| else | |
| html << "<li>" | |
| html << "<a href='##{row[:link].downcase}'>#{row[:link]}</a>" | |
| html << "</li>" | |
| end | |
| end | |
| html << "</ul>" | |
| end | |
| end | |
| require 'test/unit' | |
| class TestNestedList < Test::Unit::TestCase | |
| include UnsortedList | |
| def setup | |
| @simple = [{:nivel => "1", :link => "Uno"},{:nivel => "2", :link => "Dos"}] | |
| @complex = [{:nivel => "1", :link => "Uno"},{:nivel => "1.1", :link => "Uno Punto Uno"},{:nivel => "2", :link => "Dos"}] | |
| @more_complex = [{:nivel => "1", :link => "Uno"},{:nivel => "1.1", :link => "Uno Punto Uno"},{:nivel => "1.1.1", :link => "Uno Punto Uno Punto Uno"},{:nivel => "2", :link => "Dos"}] | |
| end | |
| def test_it_should_return_simple_list | |
| assert_equal "<ul><li><a href='#uno'>Uno</a></li><li><a href='#dos'>Dos</a></li></ul>", sort_ul(@simple) | |
| end | |
| def test_it_should_return_nested_list | |
| assert "<ul><li><a href='#uno'>Uno</a></li><ul><li><a href='#uno punto uno'>Uno Punto Uno</a></li></ul><li><a href='#dos'>Dos</a></li></ul>", sort_ul(@complex) | |
| end | |
| def test_it_should_return_complex_nested_list | |
| assert "<ul><li><a href='#uno'>Uno</a></li><ul><li><a href='#uno punto uno'>Uno Punto Uno</a><ul><li><a href='#uno punto uno punto uno'>Uno Punto Uno Punto Uno</a></li></ul></li></ul><li><a href='#dos'>Dos</a></li></ul>", sort_ul(@more_complex) | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment