Back from the Abyss: A Helper to Create Nested Lists

Posted by labrat

Sorry for not writing in a while. I've been busy doing other stuff and on top of that DreamHost has been real brutal to this Mephisto blog. My blog was inaccessible for a long long time and there really wasn't anything I could do. Support requests simply came back as "can't do anything for third party software". Oh well, I'm not complaining but it's a shame. I'm using WordPress for another blog and I've got to say it's a pleasure to use a mature blog with lots of plugins to meet every need. I'm going to be tool agnostic from now on. That's not to say I want to do PHP. Mephisto is great for seeing a top class rails coder in action.

So anyways, as lot as DreamHost lets me run this blog, I'll try to write something up.

Today, I came across a great snippet you can add in your helpers to iterate over html lists, you know the typical ol ul elements.

Which lets you write: <%= ul @pages.map { |x| link_to_page(x) } %>

Well, this is a great time saver and way better than hand-coding it yourself but I wanted something that could produce a nested list from an array of arrays. Now my code isn't the most elegant but it works. It uses recursion to produce a nested list (although the spacing and newlines aren't included so the source looks garbled in real life).

So this in your views: <%= ol ["first", "first", ["third", ["second", "second", "second"], "third", "third", ["second", "second", "second"]]] %>

Becomes:

  1. first
  2. first
    1. third
      1. second
      2. second
      3. second
    2. third
    3. third
      1. second
      2. second
      3. second

Here's the snippet:

    def html_list(type, elements, options = {})
      items = elements.map  do |element|
        if element.is_a?(Array)
          element = html_list(type, element, options = {})
        else
          content_tag("li", element)
        end
      end
      content_tag(type, items, options)
    end

Haven't tried it for something nested deeper than two elements so mileage may vary. What can you use it for? I was thinking nested comments (will have to figure that one out).

vemod.net - List Helper for Rails

Comments

Leave a response

Comment