HTML and Helpers

Look at all this code. Yikes!

Even though, in theory, you're supposed to be allowed to put HTML in your helpers, the result is that you still end up mixing up all your presentation and business logic. Some people would argue that it's not possible to separate presentation and content. I'm not arguing either way...just trying to point out that it's easy to get these things intermingled.

Anyhow, what's going on here is that a document group has a bunch of document templates. Users will have filled out some templates--in which case the "instances" of those templates become documents--and in other cases they won't have filled them out.

Originally, I was just going to do a condition based on the existence of the document or not, but then I realized this edge case that somehow a user may end up with two documents based on the same template. I'm not sure how this would happen, but could happen easily, for example, if the user bookmarked the URL for the new document page for that document template.

I suppose I could make the new action check for the existence of a document using said template for the current user, and that would almost ensure this problem wouldn't happen...from the UI. What happens if data is added directly to the database? In fact, that's how I found this case...I accidentally loaded some test data twice and my original code crapped out.

Anyhow, in my view:



    <%
    @document_group.document_templates.each do |child|
    array_of_links_to_document_if_exists_from_template(child).each do |link|
    %><li><%= link %></li><%
    end
    end
    %>


And in my helper:


def array_of_links_to_document_if_exists_from_template(document_template)
links = []
documents = Document.find(:all, :conditions => { :journal_id => @journal, :document_template_id => document_template })
if (!documents.empty?)
documents.each do |document|
links.push(link_to_remote(document.name, { :update => "dvMainPane", :url => { :controller => :documents, :action => :edit, :id => document }}))
end
else
links.push(link_to_remote(document_template.name, { :update => "dvMainPane", :url => { :controller => :documents, :action => :new, :journal_id => @journal, :document_template_id => document_template.id }}))
end
links
end

Is the helper the right place for business logic? I'm thinking right solution here isn't to put the logic in a helper...maybe helpers are really just rendering helpers...and that the logic should be in my model.

No comments: