[LRUG] Code Help

Tom Stuart tom at experthuman.com
Sat Mar 1 04:02:45 PST 2008


On 29 Feb 2008, at 14:29, Anthony Green wrote:
> def tree_to_nested_list(object, &block)
> content_tag(:ol) do
>  content_tag(:li) do
>   html = yield object if block_given?
>   html += object.children.map { |child| tree_to_nested_list(child,  
> &block)
> }.join('\n')
>   end
> end
> end

There are all sorts of changes you could make (always initialising  
html; inject vs map; append vs join; implicit block vs named block  
arg) but my main suggestion is that you've got the <li> in the wrong  
place! Leaving everything else the same, your code should probably  
look something like

def tree_to_nested_list(object, &block)
   content_tag(:ol) do
     child_to_nested_list(object, &block)
   end
end

def child_to_nested_list(object, &block)
   content_tag(:li) do
     html = yield object if block_given?
     html += content_tag(:ol, object.children.map { |child|  
child_to_nested_list(child, &block) }.join('\n')) unless  
object.children.empty?
     html
   end
end

to make the nestings of <ol>s and <li>s turn out right.

Cheers,
-Tom



More information about the Chat mailing list